" Vimball Archiver by Charles E. Campbell, Jr., Ph.D. UseVimball finish ftplugin/ATP_files/LatexBox_common.vim [[[1 313 " Author: David Munger (latexbox vim plugin) " Description: LaTeX Box common functions " Maintainer: Marcin Szamotulski " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " Language: tex " Last Change: Sat Mar 12 11:00 2011 W let s:sourced = exists("s:sourced") ? 1 : 0 " Settings {{{ " Compilation {{{ " g:vim_program {{{ if !exists('g:vim_program') " attempt autodetection of vim executable let g:vim_program = '' let tmpfile = tempname() silent execute '!ps -o command= -p $PPID > ' . tmpfile for line in readfile(tmpfile) let line = matchstr(line, '^\S\+\>') if !empty(line) && executable(line) let g:vim_program = line . ' -g' break endif endfor call delete(tmpfile) if empty(g:vim_program) if has('gui_macvim') let g:vim_program = '/Applications/MacVim.app/Contents/MacOS/Vim -g' else let g:vim_program = v:progname endif endif endif " }}} if !exists('g:LatexBox_latexmk_options') let g:LatexBox_latexmk_options = '' endif if !exists('g:LatexBox_output_type') let g:LatexBox_output_type = 'pdf' endif if !exists('g:LatexBox_viewer') let g:LatexBox_viewer = b:atp_Viewer endif if !exists('g:LatexBox_autojump') let g:LatexBox_autojump = 0 endif " }}} " Completion {{{ if !exists('g:LatexBox_completion_close_braces') let g:LatexBox_completion_close_braces = 1 endif if !exists('g:LatexBox_bibtex_wild_spaces') let g:LatexBox_bibtex_wild_spaces = 1 endif if !exists('g:LatexBox_cite_pattern') let g:LatexBox_cite_pattern = '\C\\cite\(p\|t\)\=\*\=\(\[[^\]]*\]\)*\_\s*{' endif if !exists('g:LatexBox_ref_pattern') let g:LatexBox_ref_pattern = '\C\\v\?\(eq\|page\)\?ref\*\?\_\s*{' endif if !exists('g:LatexBox_completion_environments') let g:LatexBox_completion_environments = [ \ {'word': 'itemize', 'menu': 'bullet list' }, \ {'word': 'enumerate', 'menu': 'numbered list' }, \ {'word': 'description', 'menu': 'description' }, \ {'word': 'center', 'menu': 'centered text' }, \ {'word': 'figure', 'menu': 'floating figure' }, \ {'word': 'table', 'menu': 'floating table' }, \ {'word': 'equation', 'menu': 'equation (numbered)' }, \ {'word': 'align', 'menu': 'aligned equations (numbered)' }, \ {'word': 'align*', 'menu': 'aligned equations' }, \ {'word': 'document' }, \ {'word': 'abstract' }, \ ] endif if !exists('g:LatexBox_completion_commands') let g:LatexBox_completion_commands = [ \ {'word': '\begin{' }, \ {'word': '\end{' }, \ {'word': '\item' }, \ {'word': '\label{' }, \ {'word': '\ref{' }, \ {'word': '\eqref{eq:' }, \ {'word': '\cite{' }, \ {'word': '\chapter{' }, \ {'word': '\section{' }, \ {'word': '\subsection{' }, \ {'word': '\subsubsection{' }, \ {'word': '\paragraph{' }, \ {'word': '\nonumber' }, \ {'word': '\bibliography' }, \ {'word': '\bibliographystyle' }, \ ] endif " }}} " Vim Windows {{{ if !exists('g:LatexBox_split_width') let g:LatexBox_split_width = 30 endif " }}} " }}} " Filename utilities {{{ " function! LatexBox_GetMainTexFile() " 1. check for the b:main_tex_file variable if exists('b:main_tex_file') && glob(b:main_tex_file, 1) != '' return b:main_tex_file endif " 2. scan current file for "\begin{document}" if &filetype == 'tex' && search('\C\\begin\_\s*{document}', 'nw') != 0 return expand('%:p') endif " 3. prompt for file with completion let b:main_tex_file = s:PromptForMainFile() return b:main_tex_file endfunction function! s:PromptForMainFile() let saved_dir = getcwd() execute 'cd ' . expand('%:p:h') let l:file = '' while glob(l:file, 1) == '' let l:file = input('main LaTeX file: ', '', 'file') if l:file !~ '\.tex$' let l:file .= '.tex' endif endwhile execute 'cd ' . saved_dir return l:file endfunction " Return the directory of the main tex file function! LatexBox_GetTexRoot() return fnamemodify(LatexBox_GetMainTexFile(), ':h') endfunction function! LatexBox_GetTexBasename(with_dir) if a:with_dir return fnamemodify(LatexBox_GetMainTexFile(), ':r') else return fnamemodify(LatexBox_GetMainTexFile(), ':t:r') endif endfunction function! LatexBox_GetAuxFile() return LatexBox_GetTexBasename(1) . '.aux' endfunction function! LatexBox_GetLogFile() return LatexBox_GetTexBasename(1) . '.log' endfunction function! LatexBox_GetOutputFile() return LatexBox_GetTexBasename(1) . '.' . g:LatexBox_output_type endfunction " }}} " View Output {{{ function! LatexBox_View() let outfile = LatexBox_GetOutputFile() if !filereadable(outfile) echomsg fnamemodify(outfile, ':.') . ' is not readable' return endif let cmd = '!' . g:LatexBox_viewer . ' ' . shellescape(outfile) . ' &>/dev/null &' if has("gui_running") silent execute cmd else execute cmd endif endfunction command! LatexView call LatexBox_View() " }}} " In Comment {{{ " LatexBox_InComment([line], [col]) " return true if inside comment function! LatexBox_InComment(...) let line = a:0 >= 1 ? a:1 : line('.') let col = a:0 >= 2 ? a:2 : col('.') return synIDattr(synID(line("."), col("."), 0), "name") =~# '^texComment' endfunction " }}} " Get Current Environment {{{ " LatexBox_GetCurrentEnvironment([with_pos]) " Returns: " - environment if with_pos is not given " - [envirnoment, lnum_begin, cnum_begin, lnum_end, cnum_end] if with_pos is nonzero function! LatexBox_GetCurrentEnvironment(...) if a:0 > 0 let with_pos = a:1 else let with_pos = 0 endif let begin_pat = '\C\\begin\_\s*{[^}]*}\|\\\@ 1 && line[cnum - 1] != '\' let cnum -= 1 endwhile call cursor(lnum, cnum) " match begin/end pairs but skip comments let flags = 'bnW' if strpart(getline('.'), col('.') - 1) =~ '^\%(' . begin_pat . '\)' let flags .= 'c' endif let [lnum1, cnum1] = searchpairpos(begin_pat, '', end_pat, flags, 'LatexBox_InComment()') let env = '' if lnum1 let line = strpart(getline(lnum1), cnum1 - 1) if empty(env) let env = matchstr(line, '^\C\\begin\_\s*{\zs[^}]*\ze}') endif if empty(env) let env = matchstr(line, '^\\\[') endif if empty(env) let env = matchstr(line, '^\\(') endif endif if with_pos == 1 let flags = 'nW' if !(lnum1 == lnum && cnum1 == cnum) let flags .= 'c' endif let [lnum2, cnum2] = searchpairpos(begin_pat, '', end_pat, flags, 'LatexBox_InComment()') call setpos('.', saved_pos) return [env, lnum1, cnum1, lnum2, cnum2] else call setpos('.', saved_pos) return env endif endfunction " }}} " Tex To Tree {{{ " stores nested braces in a tree structure function! LatexBox_TexToTree(str) let tree = [] let i1 = 0 let i2 = -1 let depth = 0 while i2 < len(a:str) let i2 = match(a:str, '[{}]', i2 + 1) if i2 < 0 let i2 = len(a:str) endif if i2 >= len(a:str) || a:str[i2] == '{' if depth == 0 let item = substitute(strpart(a:str, i1, i2 - i1), '^\s*\|\s*$', '', 'g') if !empty(item) call add(tree, item) endif let i1 = i2 + 1 endif let depth += 1 else let depth -= 1 if depth == 0 call add(tree, LatexBox_TexToTree(strpart(a:str, i1, i2 - i1))) let i1 = i2 + 1 endif endif endwhile return tree endfunction " }}} " Tree To Tex {{{ function! LatexBox_TreeToTex(tree) if type(a:tree) == type('') return a:tree else return '{' . join(map(a:tree, 'LatexBox_TreeToTex(v:val)'), '') . '}' endif endfunction " }}} " vim:fdm=marker:ff=unix:noet:ts=4:sw=4 ftplugin/ATP_files/LatexBox_complete.vim [[[1 383 " Author: David Mnuger (latexbox vim plugin) " Maintainer: Marcin Szamotulski " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " Email: mszamot [AT] gmail [DOT] com " Language: tex " Last Change: let s:sourced = exists("s:sourced") ? 1 : 0 if s:sourced finish endif let s:atp_MainFile = ( g:atp_RelativePath ? globpath(b:atp_ProjectDir, fnamemodify(b:atp_MainFile, ":t")) : b:atp_MainFile ) " latex-box/complete.vim " Wrap {{{ function! s:GetSID() return matchstr(expand(''), '\zs\d\+_\ze.*$') endfunction let s:SID = s:GetSID() call extend(g:atp_compiler_SID,{ fnamemodify(expand(''),':t') : s:SID }) " a:1 is the file where the function is defined. function! s:SIDWrap(func,...) return s:SID . a:func endfunction " }}} " Omni Completion {{{ let s:completion_type = '' function! LatexBox_Complete(findstart, base) if a:findstart " return the starting position of the word let line = getline('.') let pos = col('.') - 1 while pos > 0 && line[pos - 1] !~ '\\\|{' let pos -= 1 endwhile let line_start = line[:pos-1] if line_start =~ '\C\\begin\_\s*{$' let s:completion_type = 'begin' elseif line_start =~ '\C\\end\_\s*{$' let s:completion_type = 'end' elseif line_start =~ g:LatexBox_ref_pattern . '$' let s:completion_type = 'ref' elseif line_start =~ g:LatexBox_cite_pattern . '$' let s:completion_type = 'bib' " check for multiple citations let pos = col('.') - 1 while pos > 0 && line[pos - 1] !~ '{\|,' let pos -= 1 endwhile else let s:completion_type = 'command' if line[pos - 1] == '\' let pos -= 1 endif endif return pos else " return suggestions in an array let suggestions = [] if s:completion_type == 'begin' " suggest known environments for entry in g:LatexBox_completion_environments if entry.word =~ '^' . escape(a:base, '\') if g:LatexBox_completion_close_braces && !s:NextCharsMatch('^}') " add trailing '}' let entry = copy(entry) let entry.abbr = entry.word let entry.word = entry.word . '}' endif call add(suggestions, entry) endif endfor elseif s:completion_type == 'end' " suggest known environments let env = LatexBox_GetCurrentEnvironment() if env != '' if g:LatexBox_completion_close_braces && !s:NextCharsMatch('^\s*[,}]') call add(suggestions, {'word': env . '}', 'abbr': env}) else call add(suggestions, env) endif endif elseif s:completion_type == 'command' " suggest known commands for entry in g:LatexBox_completion_commands if entry.word =~ '^' . escape(a:base, '\') " do not display trailing '{' if entry.word =~ '{' let entry.abbr = entry.word[0:-2] endif call add(suggestions, entry) endif endfor elseif s:completion_type == 'ref' let suggestions = s:CompleteLabels(a:base) elseif s:completion_type == 'bib' " suggest BibTeX entries let suggestions = LatexBox_BibComplete(a:base) endif if !has('gui_running') redraw! endif return suggestions endif endfunction " }}} " BibTeX search {{{ " find the \bibliography{...} commands " the optional argument is the file name to be searched function! LatexBox_kpsewhich(file) let old_dir = getcwd() execute 'lcd ' . LatexBox_GetTexRoot() redir => out silent execute '!kpsewhich ' . a:file redir END let out = split(out, "\")[-1] let out = substitute(out, '\r', '', 'g') let out = glob(fnamemodify(out, ':p'), 1) execute 'lcd ' . fnameescape(old_dir) return out endfunction function! s:FindBibData(...) if a:0 == 0 let file = ( g:atp_RelativePath ? globpath(b:atp_ProjectDir, fnamemodify(b:atp_MainFile, ":t")) : b:atp_MainFile ) else let file = a:1 endif if empty(glob(file, 1)) return '' endif let lines = readfile(file) let bibdata_list = [] let bibdata_list += \ map(filter(copy(lines), 'v:val =~ ''\C\\bibliography\s*{[^}]\+}'''), \ 'matchstr(v:val, ''\C\\bibliography\s*{\zs[^}]\+\ze}'')') let bibdata_list += \ map(filter(copy(lines), 'v:val =~ ''\C\\\%(input\|include\)\s*{[^}]\+}'''), \ 's:FindBibData(LatexBox_kpsewhich(matchstr(v:val, ''\C\\\%(input\|include\)\s*{\zs[^}]\+\ze}'')))') let bibdata_list += \ map(filter(copy(lines), 'v:val =~ ''\C\\\%(input\|include\)\s\+\S\+'''), \ 's:FindBibData(LatexBox_kpsewhich(matchstr(v:val, ''\C\\\%(input\|include\)\s\+\zs\S\+\ze'')))') let bibdata = join(bibdata_list, ',') return bibdata endfunction let s:bstfile = expand(':p:h') . '/vimcomplete' function! LatexBox_BibSearch(regexp) " find bib data let bibdata = s:FindBibData() if bibdata == '' echomsg 'error: no \bibliography{...} command found' return endif " write temporary aux file let tmpbase = b:atp_ProjectDir . '/_LatexBox_BibComplete' let auxfile = tmpbase . '.aux' let bblfile = tmpbase . '.bbl' let blgfile = tmpbase . '.blg' call writefile(['\citation{*}', '\bibstyle{' . s:bstfile . '}', '\bibdata{' . bibdata . '}'], auxfile) let atp_MainFile = atplib#FullPath(b:atp_MainFile) silent execute '! cd ' shellescape(fnamemodify(atp_MainFile,":h")) . \ ' ; bibtex -terse ' . fnamemodify(auxfile, ':t') . ' >/dev/null' let res = [] let curentry = '' let lines = split(substitute(join(readfile(bblfile), "\n"), '\n\n\@!\(\s\=\)\s*\|{\|}', '\1', 'g'), "\n") for line in filter(lines, 'v:val =~ a:regexp') let matches = matchlist(line, '^\(.*\)||\(.*\)||\(.*\)||\(.*\)||\(.*\)') if !empty(matches) && !empty(matches[1]) call add(res, {'key': matches[1], 'type': matches[2], \ 'author': matches[3], 'year': matches[4], 'title': matches[5]}) endif endfor call delete(auxfile) call delete(bblfile) call delete(blgfile) return res endfunction " }}} " BibTeX completion {{{ function! LatexBox_BibComplete(regexp) " treat spaces as '.*' if needed if g:LatexBox_bibtex_wild_spaces "let regexp = substitute(a:regexp, '\s\+', '.*', 'g') let regexp = '.*' . substitute(a:regexp, '\s\+', '\\\&.*', 'g') else let regexp = a:regexp endif let res = [] for m in LatexBox_BibSearch(regexp) let w = {'word': m['key'], \ 'abbr': '[' . m['type'] . '] ' . m['author'] . ' (' . m['year'] . ')', \ 'menu': m['title']} " close braces if needed if g:LatexBox_completion_close_braces && !s:NextCharsMatch('^\s*[,}]') let w.word = w.word . '}' endif call add(res, w) endfor return res endfunction " }}} " Complete Labels {{{ " the optional argument is the file name to be searched function! s:CompleteLabels(regex, ...) if a:0 == 0 let atp_MainFile = atplib#FullPath(b:atp_MainFile) let file = fnamemodify(atp_MainFile, ":r") . ".aux" else let file = a:1 endif if empty(glob(file, 1)) return [] endif let suggestions = [] " search for the target equation number for line in filter(readfile(file), 'v:val =~ ''^\\newlabel{\|^\\@input{''') echomsg "matching line: " . line " search for matching label let matches = matchlist(line, '^\\newlabel{\(' . a:regex . '[^}]*\)}{{\([^}]*\)}{\([^}]*\)}.*}') if empty(matches) " also try to match label and number let regex_split = split(a:regex) if len(regex_split) > 1 let base = regex_split[0] let number = escape(join(regex_split[1:], ' '), '.') let matches = matchlist(line, '^\\newlabel{\(' . base . '[^}]*\)}{{\(' . number . '\)}{\([^}]*\)}.*}') endif endif if empty(matches) " also try to match number let matches = matchlist(line, '^\\newlabel{\([^}]*\)}{{\(' . escape(a:regex, '.') . '\)}{\([^}]*\)}.*}') endif if !empty(matches) let entry = {'word': matches[1], 'menu': '(' . matches[2] . ') [p.' . matches[3] . ']'} if g:LatexBox_completion_close_braces && !s:NextCharsMatch('^\s*[,}]') " add trailing '}' let entry = copy(entry) let entry.abbr = entry.word let entry.word = entry.word . '}' endif call add(suggestions, entry) endif " search for included files let included_file = matchstr(line, '^\\@input{\zs[^}]*\ze}') if included_file != '' let included_file = LatexBox_kpsewhich(included_file) call extend(suggestions, s:CompleteLabels(a:regex, included_file)) endif endfor return suggestions endfunction " }}} " Change Environment {{{ function! s:ChangeEnvPrompt() let [env, lnum, cnum, lnum2, cnum2] = LatexBox_GetCurrentEnvironment(1) let new_env = input('change ' . env . ' for: ', '', 'customlist,' . s:SIDWrap('GetEnvironmentList')) if empty(new_env) return endif if new_env == '\[' || new_env == '[' let begin = '\[' let end = '\]' elseif new_env == '\(' || new_env == '(' let begin = '\(' let end = '\)' else let l:begin = '\begin{' . new_env . '}' let l:end = '\end{' . new_env . '}' endif if env == '\[' || env == '\(' let line = getline(lnum2) let line = strpart(line, 0, cnum2 - 1) . l:end . strpart(line, cnum2 + 1) call setline(lnum2, line) let line = getline(lnum) let line = strpart(line, 0, cnum - 1) . l:begin . strpart(line, cnum + 1) call setline(lnum, line) else let line = getline(lnum2) let line = strpart(line, 0, cnum2 - 1) . l:end . strpart(line, cnum2 + len(env) + 5) call setline(lnum2, line) let line = getline(lnum) let line = strpart(line, 0, cnum - 1) . l:begin . strpart(line, cnum + len(env) + 7) call setline(lnum, line) endif endfunction function! s:GetEnvironmentList(lead, cmdline, pos) let suggestions = [] if !exists("b:atp_LocalEnvironments") call LocalCommands() endif let l:completion_list=atplib#Extend(g:atp_Environments,b:atp_LocalEnvironments) for entry in l:completion_list " let env = entry.word if entry =~ '^' . a:lead call add(suggestions, entry) endif endfor if len(suggestions) > 5 call sort(suggestions) endif return suggestions endfunction " }}} " Next Charaters Match {{{ function! s:NextCharsMatch(regex) let rest_of_line = strpart(getline('.'), col('.') - 1) return rest_of_line =~ a:regex endfunction " }}} " Mappings {{{ nmap LatexChangeEnv :call ChangeEnvPrompt() " }}} ftplugin/ATP_files/LatexBox_indent.vim [[[1 84 " Title: vim indent file for tex files. " Author: David Munger (mungerd@gmail.com) " Maintainer: Marcin Szamotulski " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " Language: tex " Last Change: if exists("b:did_indent") finish endif let b:did_indent = 1 setlocal indentexpr=LatexBox_TexIndent() setlocal indentkeys==\end,=\item,),],},o,O,0\\,!^F let s:itemize_envs = ['itemize', 'enumerate', 'description'] " indent on \left( and on \(, but not on ( " indent on \left[ and on \[, but not on [ " indent on \left\{ and on \{, and on { let s:open_pat = '\\begin\>\|\%(\\left\s*\)\=\\\=[{]\|\%(\\left\s*\|\\\)[[(]' let s:close_pat = '\\end\>\|\%(\\right\s*\)\=\\\=[}]\|\%(\\right\s*\|\\\)[])]' " Compute Level {{{ function! s:ComputeLevel(lnum_prev, open_pat, close_pat) let n = 0 let line_prev = getline(a:lnum_prev) " strip comments let line_prev = substitute(line_prev, '\\\@ % LatexBox_JumpToMatch xmap % LatexBox_JumpToMatch vmap ie LatexBox_SelectCurrentEnvInner vmap iE LatexBox_SelectCurrentEnVInner vmap ae LatexBox_SelectCurrentEnvOuter omap ie :normal vie omap ae :normal vae vmap im LatexBox_SelectInlineMathInner vmap am LatexBox_SelectInlineMathOuter omap im :normal vim omap am :normal vam setlocal omnifunc=LatexBox_Complete ftplugin/ATP_files/LatexBox_motion.vim [[[1 873 " Language: tex " Author: David Mnuger (latexbox vim plugin) " Maintainer: Marcin Szamotulski " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " Language: tex " Last Change: " Some things is enough to source once let s:sourced = exists("s:sourced") ? 1 : 0 if !s:sourced " HasSyntax {{{ " s:HasSyntax(syntaxName, [line], [col]) function! s:HasSyntax(syntaxName, ...) let line = a:0 >= 1 ? a:1 : line('.') let col = a:0 >= 2 ? a:2 : col('.') return index(map(synstack(line, col), 'synIDattr(v:val, "name") == "' . a:syntaxName . '"'), 1) >= 0 endfunction " }}} " Search and Skip Comments {{{ " s:SearchAndSkipComments(pattern, [flags], [stopline]) function! s:SearchAndSkipComments(pat, ...) let flags = a:0 >= 1 ? a:1 : '' let stopline = a:0 >= 2 ? a:2 : 0 let saved_pos = getpos('.') " search once let ret = search(a:pat, flags, stopline) if ret " do not match at current position if inside comment let flags = substitute(flags, 'c', '', 'g') " keep searching while in comment while LatexBox_InComment() let ret = search(a:pat, flags, stopline) if !ret break endif endwhile endif if !ret " if no match found, restore position call setpos('.', saved_pos) endif return ret endfunction " }}} " begin/end pairs {{{ " " s:JumpToMatch(mode, [backward]) " - search backwards if backward is given and nonzero " - search forward otherwise " function! s:JumpToMatch(mode, ...) if a:0 >= 1 let backward = a:1 else let backward = 0 endif let sflags = backward ? 'cbW' : 'cW' " selection is lost upon function call, reselect if a:mode == 'v' normal! gv endif " open/close pairs (dollars signs are treated apart) let open_pats = ['{', '\[', '(', '\\begin\>', '\\left\>'] let close_pats = ['}', '\]', ')', '\\end\>', '\\right\>'] let dollar_pat = '\\\@' ? line('.') : 0 ) " go to next opening/closing pattern on same line if !s:HasSyntax('texSectionModifier', line('.'), col('.')) let pos = !s:SearchAndSkipComments( \ '\m\C\%(' . join(open_pats + close_pats + [dollar_pat], '\|') . '\)', \ sflags, stopline) else let pos = !s:SearchAndSkipComments( \ '\m\C\%(' . join(open_pats + close_pats, '\|') . '\)', \ sflags, stopline) endif " THE line('.') above blocks it from workin not just in one line " (especially with \begin:\end which might be in different lines). if pos " abort if no match or if match is inside a comment call setpos('.', saved_pos) return endif let rest_of_line = strpart(getline('.'), col('.') - 1) " match for '$' pairs if rest_of_line =~ '^\$' && !s:HasSyntax('texSectionModifier', line('.'), col('.')) " check if next character is in inline math let zonex+=s:HasSyntax('texMathZoneX', line("."), col(".")) let zoney+=s:HasSyntax('texMathZoneY', line("."), col(".")) || s:HasSyntax('texMathZoneY', line('.'), max([1, col(".")-1])) let [lnum, cnum] = searchpos('.', 'nW') if zonex if lnum && s:HasSyntax('texMathZoneX', lnum, cnum) call s:SearchAndSkipComments(dollar_pat, 'W') else call s:SearchAndSkipComments(dollar_pat, 'bW') endif elseif zoney if lnum && s:HasSyntax('texMathZoneY', lnum, cnum) call s:SearchAndSkipComments(two_dollar_pat, 'W') else call s:SearchAndSkipComments(two_dollar_pat, 'bW') endif endif else " match other pairs for i in range(len(open_pats)) let open_pat = open_pats[i] let close_pat = close_pats[i] if rest_of_line =~ '^\C\%(' . open_pat . '\)' " if on opening pattern, go to closing pattern call searchpair('\C' . open_pat, '', '\C' . close_pat, 'W', 'LatexBox_InComment()') break elseif rest_of_line =~ '^\C\%(' . close_pat . '\)' " if on closing pattern, go to opening pattern call searchpair('\C' . open_pat, '', '\C' . close_pat, 'bW', 'LatexBox_InComment()') break endif endfor endif endfunction nnoremap LatexBox_JumpToMatch :call JumpToMatch('n') vnoremap LatexBox_JumpToMatch :call JumpToMatch('v') nnoremap LatexBox_BackJumpToMatch :call JumpToMatch('n', 1) vnoremap LatexBox_BackJumpToMatch :call JumpToMatch('v', 1) " }}} " select inline math {{{ " s:SelectInlineMath(seltype) " where seltype is either 'inner' or 'outer' function! s:SelectInlineMath(seltype) let saved_pos = getpos('.') let synstack = map(synstack(line("."),col(".")), 'synIDattr(v:val, "name")') if len(filter(synstack, "v:val =~ '^texMathZone[A-L]S\\?'")) call s:SelectCurrentEnv(a:seltype) return endif let ZoneX_pat_O = '\\\@ 1 normal! h elseif ( s:HasSyntax('texMathZoneV', line("."), max([1,col(".")-2])) || \ s:HasSyntax('texMathZoneW', line("."), max([1,col(".")-2])) || \ s:HasSyntax('texMathZoneY', line("."), max([1,col(".")-2])) && b:atp_TexFlavor == 'plaintex' ) && \ col(".") > 2 normal! 2h endif let return = 1 let math_zones = ( b:atp_TexFlavor == 'plaintex' ? [ 'V', 'W', 'X', 'Y'] : [ 'V', 'W', 'X'] ) for L in math_zones if s:HasSyntax('texMathZone'. L, line(".")) || \ s:HasSyntax('texMathZone'. L, line("."), max([1, col(".")-1])) call s:SearchAndSkipComments(Zone{L}_pat_O, 'cbW') let zone = L let return = 0 endif endfor if return call cursor(saved_pos[1], saved_pos[2]) return endif if a:seltype == 'inner' if zone =~ '^V\|W$' || zone == 'Y' && b:atp_TexFlavor == 'plaintex' normal! 2l elseif zone == 'X' normal! l endif if getline(".")[col(".")-1] == ' ' normal! w endif endif if visualmode() ==# 'V' normal! V else normal! v endif call s:SearchAndSkipComments(Zone{zone}_pat_C, 'W') if a:seltype == 'inner' if getline(".")[col(".")-2] == ' ' normal! ge else if col(".") > 1 call cursor(line("."),col(".")-1) else call cursor(line(".")-1, len(getline(line(".")-1))) endif endif endif if a:seltype == 'outer' && zone == 'Y' call cursor(line("."),col(".")+1) endif endfunction vnoremap LatexBox_SelectInlineMathInner :call SelectInlineMath('inner') vnoremap LatexBox_SelectInlineMathOuter :call SelectInlineMath('outer') " }}} " {{{ select syntax " syntax groups 'texDocZone' and 'texSectionZone' need to be synchronized " before ':syntax sync fromstart' which is quite slow. It is better to provide " other method of doing this. (If s:SelectSyntax is not syncing the syntax " then the behaviour is unpredictable). function! s:SelectSyntax(syntax) " mark the current position normal! m' let synstack = map(synstack(line("."),col(".")), 'synIDattr(v:val, "name")') " there are better method for texDocZone and texSectionZone: call filter(synstack, "v:val != 'texDocZone' && v:val != 'texSectionZone'") if synstack == [] return endif if a:syntax == 'inner' let len = len(synstack) let syntax = synstack[max([0, len-1])] elseif a:syntax == 'outer' let syntax = synstack[0] else let syntax = a:syntax endif let save_ww = &l:ww set ww +=b,l let save_pos = getpos(".") if !count(map(synstack(line("."),col(".")), 'synIDattr(v:val, "name")'), syntax) return endif while count(map(synstack(line("."),col(".")), 'synIDattr(v:val, "name")'), syntax) normal! h " for some syntax groups do not move to previous line if col(".") == 1 && count(['texStatement', 'texTypeSize'], syntax) keepjumps normal! h break endif endwhile " begin offset if getpos(".")[2] < len(getline(".")) call cursor(line("."),col(".")+1) else call cursor(line(".")+1, 1) endif if visualmode() ==# 'V' normal! V else normal! v endif call cursor(save_pos[1], save_pos[2]) while count(map(synstack(line("."),max([1, min([col("."), len(getline("."))])])), 'synIDattr(v:val, "name")'), syntax) || len(getline(".")) == 0 keepjumps normal! l " for some syntax groups do not move to next line if col(".") == len(getline(".")) && count(['texStatement', 'texTypeSize'], syntax) keepjumps normal! l break endif endwhile " end offset if len(getline(".")) == 0 call cursor(line(".")-1,len(getline(line(".")-1))) endif if count(['texParen', 'texLength', 'Delimiter', 'texStatement', 'texTypeSize', 'texRefZone', 'texSectionMarker', 'texTypeStyle'], syntax) if col(".") > 1 call cursor(line("."),col(".")-1) else call cursor(line(".")-1,len(getline(line(".")-1))) endif elseif count(['texMathZoneV', 'texMathZoneW', 'texMathZoneY'], syntax) call cursor(line("."),col(".")+1) endif let &l:ww = save_ww endfunction " }}} " select current environment {{{ function! s:SelectCurrentEnv(seltype) let [env, lnum, cnum, lnum2, cnum2] = LatexBox_GetCurrentEnvironment(1) call cursor(lnum, cnum) if a:seltype == 'inner' if env =~ '^\' call search('\\.\_\s*\S', 'eW') else call search('}\%(\_\s*\[\_[^]]*\]\)\?\_\s*\S', 'eW') endif endif if visualmode() ==# 'V' normal! V else normal! v endif call cursor(lnum2, cnum2) if a:seltype == 'inner' call search('\S\_\s*', 'bW') else if env =~ '^\' normal! l else call search('}', 'eW') endif endif endfunction function! s:SelectCurrentEnV() call s:SelectCurrentEnv('inner') execute 'normal o' call s:JumpToMatch('n', 1) execute 'normal o' endfunction " }}} " Jump to the next braces {{{ " function! LatexBox_JumpToNextBraces(backward) let flags = '' if a:backward normal h let flags .= 'b' else let flags .= 'c' endif if search('[][}{]', flags) > 0 normal l endif let prev = strpart(getline('.'), col('.') - 2, 1) let next = strpart(getline('.'), col('.') - 1, 1) if next =~ '[]}]' && prev !~ '[][{}]' return "\" else return '' endif endfunction " }}} " Highlight Matching Pair {{{ " TODO: Redefine NoMatchParen and DoMatchParen functions to handle " s:HighlightMatchingPair function. " TODO: do not match for \begin{document}:\end{document} " or limit matches to the window (anyway it is done every time the " cursor moves). " winheight(0) returns window height " winsaveview()['topline'] returns the top line function! s:HighlightMatchingPair() 2match none if LatexBox_InComment() return endif " let open_pats = ['\\begin\>\ze\%(\s*{\s*document\s*}\)\@!', '\\left\>', '\c\\bigg\=\>\%((\|{\|\\{\|\[\)' ] " let close_pats = ['\\end\>\ze\%(\s*{\s*document\s*}\)\@!', '\\right\>', '\c\\bigg\=\>\%()\|}\|\\}\|\]\)' ] let open_pats = ['\\begin\>\ze', '\\left\>', '\c\\bigg\=l\=\>\%((\|{\|\\{\|\[\)' ] let close_pats = ['\\end\>\ze', '\\right\>', '\c\\bigg\=r\=\>\%()\|}\|\\}\|\]\)' ] let dollar_pat = '\\\@= 1 call cursor(line("."), col(".")-2) else call cursor(line(".")-1, 1) call cursor(line("."), col("$")) endif call s:SearchAndSkipComments(two_dollar_pat, 'bW') endif let cnum_e = cnum+1 let cnum_E = col('.') let cnum_Ee = cnum_E+1 execute '2match MatchParen /\%(\%' . lnum . 'l\%' . cnum . 'c\$' \ . '\|\%' . lnum . 'l\%' . cnum_e . 'c\$' \ . '\|\%' . line('.') . 'l\%' . cnum_E . 'c\$' \ . '\|\%' . line('.') . 'l\%' . cnum_Ee . 'c\$\)/' endif else " match other pairs " find first non-alpha character to the left on the same line let [lnum, cnum] = searchpos('\A', 'cbW', line('.')) if strpart(getline(lnum), 0, cnum) =~ '\\\%(begin\|end\){[^}]*}\=$' let [lnum, cnum] = searchpos('\\', 'cbW', line('.')) endif let delim = matchstr(getline(lnum), '^\m\(' . join(open_pats + close_pats, '\|') . '\)', cnum - 1) if empty(delim) call setpos('.', saved_pos) return endif for i in range(len(open_pats)) let open_pat = open_pats[i] let close_pat = close_pats[i] if delim =~# '^' . open_pat " if on opening pattern, go to closing pattern let stop_line=winheight(0)+winsaveview()['topline'] call searchpair('\C' . open_pat, '', '\C' . close_pat, 'W', 'LatexBox_InComment()', stop_line) execute '2match MatchParen /\%(\%' . lnum . 'l\%' . cnum . 'c' . open_pats[i] \ . '\|\%' . line('.') . 'l\%' . col('.') . 'c' . close_pats[i] . '\)/' break elseif delim =~# '^' . close_pat " if on closing pattern, go to opening pattern let stop_line=winsaveview()['topline'] if close_pat =~ '\\end' call searchpair('\C\\begin\>', '', '\C\\end\>\zs' , 'bW', 'LatexBox_InComment()', stop_line) else call searchpair('\C' . open_pat, '', '\C' . close_pat, 'bW', 'LatexBox_InComment()', stop_line) endif execute '2match MatchParen /\%(\%' . line('.') . 'l\%' . col('.') . 'c' . open_pats[i] \ . '\|\%' . lnum . 'l\%' . cnum . 'c' . close_pats[i] . '\)/' break endif endfor endif call setpos('.', saved_pos) endfunction " }}} " select current paragraph {{{ function! s:InnerSearchPos(begin, line, col, run) let cline = line(".") let ccol = col(".") call cursor(a:line, a:col) if a:begin == 1 let flag = 'bnW' . (a:run == 1 ? 'c' : '') " Note: sometimes it is better is it stops before \\begin some times not, " maybe it is better to decide for which environment names to stop " (theorem, ... but not align [mathematical ones]). The same about end few " lines ahead. let pattern = '\%(^\s*$' . \ '\|\\begin\>\s*{' . \ '\|\\\@' . \ '\|\ze\\newline\>' . \ '\|\\end\s*{[^}]*}\s*\zs' . \ '\)' . \ '\|\\item\%(\s*\[[^\]]*\]\)\=' . \ '\|\\\%(part\*\=' . \ '\|chapter\*\=' . \ '\|section\*\=' . \ '\|subsection\*\=' . \ '\|subsubsection\*\=' . \ '\|paragraph\*\=' . \ '\|subparagraph\*\=\)\s*\%(\[[^]]*\]\)\=\s*{[^}]*}\s*\%({^}]*}\)\=' . \ '\|\\opening{[^}]*}' . \ '\|\\closing{' . \ '\|\\\@\s*{' . \ '\|^[^%]*\%(' . \ '\zs\%(^\s\+\)\=\\par\>' . \ '\|\zs\(^\s\+\)\=\\newline\>' . \ '\|\%(^\s\+\)\=\\begin\s*{[^}]*}\s*\%(\[[^]]*\]\)\=\)' . \ '\|\%(^\%(\s\|%\)\+\)\=\\item' . \ '\|\%(^\s\+\)\=\\\%(part\*\=' . \ '\|chapter\*\=' . \ '\|section\*\=' . \ '\|subsection\*\=' . \ '\|\\)' let pattern = '\%(^\s*$' . \ '\|^[^%]*\%(\\\zepar\>' . \ '\|\\\zenewline\>' . \ '\|\\end\s*{[^}]*}\s*' . \ '\|\\begin\s*{[^}]*}\s*\%(\%({' . \ '\|\[\)[^]}]*\%(\]' . \ '\|}\)\)\=\s*\%({[^}]*}\)\=\s*\%(\%(\\label\s*{[^}]*}\)\s*\%(\\footnote\s*\%(\n' . \ '\|[^}]\)*}\)\=' . \ '\|\s*\%(\\footnote\s*\%(\n' . \ '\|[^}]\)*}\)\s*\%(\\label\s*{[^}]*}\)\=\)\=\)' . \ '\|\\item\%(\s*\[[^\]]*\]\)\=' . \ '\|\\\%(part\*\=' . \ '\|chapter\*\=' . \ '\|section\*\=' . \ '\|subsection\*\=' . \ '\|subsubsection\*\=' . \ '\|paragraph\*\=' . \ '\|subparagraph\*\=\)\s*\%(\[[^]]*\]\)\=\s*{[^}]*}\s*\%({^}]*}\)\=' . \ '\|\\opening{[^}]*}' . \ '\|\\closing{' . \ '\|\\\@' && bcol > 1 let bcol -= 1 endif if g:atp_debugSCP echomsg 'B End of Match: ' . string([bline, bcol]) endif call cursor(cline, ccolumn) " Find end position (iterate over math zones). let [ eline, ecol ] = s:InnerSearchPos(0, line("."), col("."), 1) let line = strpart(getline(eline), ecol-1) let true = atplib#CheckSyntaxGroups(g:atp_MathZones, eline, ecol) && line !~ '^\\\[' let i = 2 if g:atp_debugSCP echomsg " E pos:" . string([line("."), col(".")]) . " e-pos:" . string([eline, ecol]) . " true: " . true endif while true let line = strpart(getline(eline), ecol-1) if line =~ '^\\\@\|\\begin\s*{\s*\%(document\|letter\)\s*}', 'bcnW') let [ eline, ecol ] = searchpos('^\s*$\|^[^%]*\zs\\par\>\|\\end\s*{\s*\%(document\|letter\)\s*}\zs', 'nW') endif if g:atp_debugSCP let [ g:bline, g:bcol] = deepcopy([ bline, bcol]) let [ g:eline, g:ecol] = deepcopy([ eline, ecol]) endif let bline_str = strpart(getline(bline), bcol-1) let eline_str = strpart(getline(eline), 0, ecol) let eeline_str = strpart(getline(eline), ecol-1) if g:atp_debugSCP let g:bline_str = bline_str let g:eline_str = eline_str let g:eeline_str = eeline_str endif if getline(bline) =~ '\\par\|\\newline\|\\begin\s*{\s*\%(document\|letter\)\s*}' || bline_str =~ '^\%(\\\[\|\\item\>\)' " move to the beginning of \par let bmove = '' else " or to the begining of line let bmove = "w" endif if getline(eline) =~ '\\par' let emove = 'gE' elseif eline_str =~ '\\@' . start_lnum . 'l\%>' . start_cnum . 'c' . '\%<' . stop_lnum . 'l\%<' . stop_cnum . 'c') let [start_lnum, start_cnum] = searchpos('\\\%(textbf{\|bf\)\zs', 'W', end_line) endwhile keepjumps call setpos( '.', saved_pos) " return [start_lnum, start_cnum, stop_lnum, stop_cnum] endfunction " the 2match function can be run once: " call s:HighlightEmphText() " augroup HighlightEmphText " " Replace all matchparen autocommands " autocmd CursorMoved *.tex call HighlightEmphText() " augroup END " }}} endif " Mappings: vnoremap SelectInnerSyntax :call SelectSyntax('inner') vnoremap SelectOuterSyntax :call SelectSyntax('outer') vnoremap LatexBox_SelectCurrentEnvInner :call SelectCurrentEnv('inner') vnoremap LatexBox_SelectCurrentEnVInner :call SelectCurrentEnV() vnoremap LatexBox_SelectCurrentEnvOuter :call SelectCurrentEnv('outer') vnoremap ATP_SelectCurrentParagraphInner :call SelectCurrentParagraph('inner') vnoremap ATP_SelectCurrentParagraphOuter :call SelectCurrentParagraph('outer') vmap vSelectComment :call SelectComment() "}}} ftplugin/ATP_files/LatexBox_latexmk.vim [[[1 219 " Author: David Munger (mungerd@gmail.com) " Maintainer: Marcin Szamotulski " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " Language: tex " Last Change: let s:sourced = exists("s:sourced") ? 1 : 0 if !s:sourced " Wrap {{{ function! s:GetSID() return matchstr(expand(''), '\zs\d\+_\ze.*$') endfunction let s:SID = s:GetSID() function! s:SIDWrap(func) return s:SID . a:func endfunction " }}} " dictionary of latexmk PID's (basename: pid) let s:latexmk_running_pids = {} " Set PID {{{ function! s:LatexmkSetPID(basename, pid) let s:latexmk_running_pids[a:basename] = a:pid endfunction " }}} " Callback {{{ function! s:LatexmkCallback(basename, status) "let pos = getpos('.') if a:status echomsg "latexmk exited with status " . a:status else echomsg "latexmk finished" endif call remove(s:latexmk_running_pids, a:basename) call LatexBox_LatexErrors(g:LatexBox_autojump && a:status, a:basename) "call setpos('.', pos) endfunction " }}} " Latexmk {{{ function! LatexBox_Latexmk(force) if empty(v:servername) echoerr "cannot run latexmk in background without a VIM server" return endif let basename = LatexBox_GetTexBasename(1) if has_key(s:latexmk_running_pids, basename) echomsg "latexmk is already running for `" . fnamemodify(basename, ':t') . "'" return endif let callsetpid = s:SIDWrap('LatexmkSetPID') let callback = s:SIDWrap('LatexmkCallback') let l:options = '-' . g:LatexBox_output_type . ' -quiet ' . g:LatexBox_latexmk_options if a:force let l:options .= ' -g' endif let l:options .= " -e '$pdflatex =~ s/ / -file-line-error /'" let l:options .= " -e '$latex =~ s/ / -file-line-error /'" " callback to set the pid let vimsetpid = g:vim_program . ' --servername ' . v:servername . ' --remote-expr ' . \ shellescape(callsetpid) . '\(\"' . fnameescape(basename) . '\",$$\)' " latexmk command " wrap width in log file let max_print_line = 2000 let cmd = 'cd ' . shellescape(b:atp_ProjectDir) . ' ; max_print_line=' . max_print_line . \ ' latexmk ' . l:options . ' ' . shellescape(b:atp_MainFile) " callback after latexmk is finished let vimcmd = g:vim_program . ' --servername ' . v:servername . ' --remote-expr ' . \ shellescape(callback) . '\(\"' . fnameescape(basename) . '\",$?\)' silent execute '! ( ' . vimsetpid . ' ; ( ' . cmd . ' ) ; ' . vimcmd . ' ) &' endfunction " }}} " LatexmkStop {{{ function! LatexBox_LatexmkStop() let basename = LatexBox_GetTexBasename(1) if !has_key(s:latexmk_running_pids, basename) echomsg "latexmk is not running for `" . fnamemodify(basename, ':t') . "'" return endif call s:kill_latexmk(s:latexmk_running_pids[basename]) call remove(s:latexmk_running_pids, basename) echomsg "latexmk stopped for `" . fnamemodify(basename, ':t') . "'" endfunction " }}} " kill_latexmk {{{ function! s:kill_latexmk(gpid) " This version doesn't work on systems on which pkill is not installed: "!silent execute '! pkill -g ' . pid " This version is more portable, but still doesn't work on Mac OS X: "!silent execute '! kill `ps -o pid= -g ' . pid . '`' " Since 'ps' behaves differently on different platforms, we must use brute force: " - list all processes in a temporary file " - match by process group ID " - kill matches let pids = [] let tmpfile = tempname() silent execute '!ps x -o pgid,pid > ' . tmpfile for line in readfile(tmpfile) let pid = matchstr(line, '^\s*' . a:gpid . '\s\+\zs\d\+\ze') if !empty(pid) call add(pids, pid) endif endfor call delete(tmpfile) if !empty(pids) silent execute '! kill ' . join(pids) endif endfunction " }}} " kill_all_latexmk {{{ function! s:kill_all_latexmk() for gpid in values(s:latexmk_running_pids) call s:kill_latexmk(gpid) endfor let s:latexmk_running_pids = {} endfunction " }}} " LatexmkClean {{{ function! LatexBox_LatexmkClean(cleanall) if a:cleanall let l:options = '-C' else let l:options = '-c' endif let l:cmd = 'cd ' . shellescape(LatexBox_GetTexRoot()) . ' ; latexmk ' . l:options \ . ' ' . shellescape(LatexBox_GetMainTexFile()) silent execute '! ' . l:cmd echomsg "latexmk clean finished" endfunction " }}} " LatexmkStatus {{{ function! LatexBox_LatexmkStatus(detailed) if a:detailed if empty(s:latexmk_running_pids) echo "latexmk is not running" else let plist = "" for [basename, pid] in items(s:latexmk_running_pids) if !empty(plist) let plist .= '; ' endif let plist .= fnamemodify(basename, ':t') . ':' . pid endfor echo "latexmk is running (" . plist . ")" endif else let basename = LatexBox_GetTexBasename(1) if has_key(s:latexmk_running_pids, basename) echo "latexmk is running" else echo "latexmk is not running" endif endif endfunction " }}} " LatexErrors {{{ " LatexBox_LatexErrors(jump, [basename]) function! LatexBox_LatexErrors(jump, ...) if a:0 >= 1 let log = a:1 . '.log' else let log = LatexBox_GetLogFile() endif if (a:jump) execute 'cfile ' . fnameescape(log) else execute 'cgetfile ' . fnameescape(log) endif endfunction " }}} endif " Commands {{{ command! -buffer Latexmk call LatexBox_Latexmk(0) command! -buffer LatexmkForce call LatexBox_Latexmk(1) command! -buffer LatexmkClean call LatexBox_LatexmkClean(0) command! -buffer LatexmkCleanAll call LatexBox_LatexmkClean(1) command! -buffer LatexmkStatus call LatexBox_LatexmkStatus(0) command! -buffer LatexmkStatusDetailed call LatexBox_LatexmkStatus(1) command! -buffer LatexmkStop call LatexBox_LatexmkStop() command! -buffer LatexErrors call LatexBox_LatexErrors(1) " }}} autocmd VimLeavePre * call kill_all_latexmk() " vim:fdm=marker:ff=unix:noet:ts=4:sw=4 ftplugin/ATP_files/project.vim [[[1 754 " Author: Marcin Szamotulski " Description: A vim script which stores values of variables in a project script. " It is read, and written via autocommands. " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " Language: tex " Last Change: let s:sourced = exists("s:sourced") ? 1 : 0 " Variables: " Variables {{{ " If the user set g:atp_RelativePath " if exists("g:atp_RelativePath") && g:atp_RelativePath " setl noautochdir " endif let s:file = expand(':p') " This gives some debug info: which project scripts are loaded, loading time, " which project scripts are written. " Debug File: /tmp/ATP_ProjectScriptDebug.vim / only for s:WriteProjectScript() / if !exists("g:atp_debugProject") let g:atp_debugProject = 0 endif if !exists("g:atp_debugLPS") " debug LoadProjectScript (project.vim) let g:atp_debugLPS = 0 endif if !exists("g:atp_RelativePath") let g:atp_RelativePath = 1 endif " Also can be set in vimrc file or atprc file! (tested) " The default value (0) is set in options.vim " Windows version: let s:windows = has("win16") || has("win32") || has("win64") || has("win95") " This variable is set if the projectr script was loaded by s:LoadScript() " function. " s:project_Load = { type : 0/1 } if !exists("s:project_Load") " Load once in s:LoadScript() function let s:project_Load = {} let g:project_Load = s:project_Load endif if !exists("g:atp_CommonScriptDirectory") let g:atp_CommonScriptDirectory = expand(':p:h') endif if !isdirectory(g:atp_CommonScriptDirectory) " Make common script dir if it doesn't exist (and all intermediate directories). call mkdir(g:atp_CommonScriptDirectory, "p") endif " Mimic names of vim view files let s:common_project_script = s:windows ? g:atp_CommonScriptDirectory . '\common_var.vim' : g:atp_CommonScriptDirectory . '/common_var.vim' " These local variables will be saved: let g:atp_cached_local_variables = [ \ 'b:atp_MainFile', \ 'b:atp_ProjectScript', \ 'b:atp_LocalCommands', 'b:atp_LocalEnvironments', \ 'b:atp_LocalColors', \ 'b:TreeOfFiles', 'b:ListOfFiles', \ 'b:TypeDict', 'b:LevelDict', \ ] " Note: b:atp_ProjectDir is not here by default by the following reason: it is " specific to the host, without it sharing the project file is possible. " b:atp_PackageList is another variable that could be put into project script. " This are common variable to all tex files. let g:atp_cached_common_variables = ['g:atp_latexpackages', 'g:atp_latexclasses', 'g:atp_Library'] " }}} " Autocommands: augroup ATP_ProjectFile au! au BufWritePre *.tex.project.vim if has("persistent_undo") | setlocal noundofile | endif augroup END " Functions: (soure once) if !s:sourced || g:atp_reload_functions "{{{ " Load Script: "{{{ s:LoadScript(), :LoadScript, autocommads " s:LoadScript({bang}, {project_script}, {type}, {load_variables}, [silent], [ch_load]) " " a:bang == "!" ignore texmf tree and ignore b:atp_ProjectScript, g:atp_ProjectScript " variables " a:project_script file to source " a:type = 'local'/'global' " a:load_variabels load variables after loading project script " can be used on startup to load variables which depend " on things set in project script. " a:1 = 'silent'/'' echo messages " a:2 = ch_load check if project script was already loaded " a:3 = ignore ignore b:atp_ProjectScript and g:atp_ProjectScript variables " used by commands function! LoadScript(bang, project_script, type, load_variables, ...) "{{{ if g:atp_debugProject redir! >> /tmp/ATP_ProjectScriptDebug.vim let hist_time = reltime() echomsg "\n" echomsg "ATP_ProjectScript: LoadScript " . a:type . " file " . string(a:project_script) endif let silent = a:0 >= 1 ? a:1 : "0" let silent = silent || silent == "silent" ? "silent" : "" let ch_load = a:0 >= 2 ? a:2 : 0 let ignore = a:0 >= 3 ? a:3 : 0 " Is project script on/off " The local variable overrides the global ones! " Note: " When starting the vim b:atp_ProjectScript might not be yet defined (will be " defined later, and g:atp_ProjectScript might already be defined, so not always " global variables override local ones). " Global variable overrides local one if !ignore && ( exists("g:atp_ProjectScript") && !g:atp_ProjectScript || exists("b:atp_ProjectScript") && ( !b:atp_ProjectScript && (!exists("g:atp_ProjectScript") || exists("g:atp_ProjectScript") && !g:atp_ProjectScript )) ) exe silent . ' echomsg "ATP LoadScirpt: not loading project script."' if g:atp_debugProject echomsg "b:atp_ProjectScript=" . ( exists("b:atp_ProjectScript") ? b:atp_ProjectScript : -1 ) . " g:atp_ProjectScript=" . ( exists("g:atp_ProjectScript") ? g:atp_ProjectScript : -1 ) . "\n" echomsg "ATP_ProjectScript : END " !ignore redir END endif return endif " Load once feature (if ch_load) - this is used on starup if ch_load && get(get(s:project_Load, expand("%:p"), []), a:type, 0) >= 1 echomsg "Project script " . a:type . " already loaded for this buffer." if g:atp_debugProject redir END endif return endif let cond_A = get(s:project_Load, expand("%:p"), 0) let cond_B = get(get(s:project_Load, expand("%:p"), []), a:type, 0) if empty(expand("%:p")) echohl ErrorMsg echomsg "ATP Error : File name is empty. Not loading project script." echohl Normal if g:atp_debugProject redir END endif return endif if cond_B let s:project_Load[expand("%:p")][a:type][0] += 1 elseif cond_A let s:project_Load[expand("%:p")] = { a:type : 1 } else let s:hisotory_Load= { expand("%:p") : { a:type : 1 } } endif if a:bang == "" && expand("%:p") =~ 'texmf' if g:atp_debugProject redir END endif return endif let b:atp_histloaded=1 if a:type == "local" let save_loclist = getloclist(0) try silent exe 'lvimgrep /\Clet\s\+b:atp_ProjectScript\>\s*=/j ' . fnameescape(a:project_script) catch /E480:/ endtry let loclist = getloclist(0) call setloclist(0, save_loclist) execute get(get(loclist, 0, {}), 'text', "") if exists("b:atp_ProjectScript") && !b:atp_ProjectScript if g:atp_debugProject silent echomsg "ATP_ProjectScript: b:atp_ProjectScript == 0 in the project script." redir END endif return endif endif " Load first b:atp_ProjectScript variable try if filereadable(a:project_script) execute "silent! source " . fnameescape(a:project_script) endif if g:atp_debugProject echomsg "ATP_ProjectScript: sourcing " . a:project_script endif catch /E484:/ endtry if g:atp_debugProject echomsg "ATP_ProjectScript: sourcing time: " . reltimestr(reltime(hist_time)) redir! END endif if a:load_variables if !exists("b:atp_project") if exists("b:LevelDict") && max(values(filter(deepcopy(b:LevelDict), "get(b:TypeDict, v:key, '')=='input'"))) >= 1 let b:atp_project = 1 else let b:atp_project = 0 endif endif endif " if a:type == 'local' " call TEST() " endif endfunction "}}} " This functoin finds recursilevy (upward) all project scripts. " {{{ FindProjectScripts() function! FindProjectScripts() let dir = fnamemodify(resolve(expand("%:p")), ":p:h") let g:dir = dir let cwd = getcwd() exe "lcd " . fnameescape(dir) while glob('*.project.vim', 1) == '' let dir_l = dir let dir = fnamemodify(dir, ":h") if dir == $HOME || dir == dir_l break endif exe "lcd " . fnameescape(dir) endwhile let project_files = map(split(glob('*project.vim', 1), "\n"), "fnamemodify(v:val, \":p\")") exe "lcd " . fnameescape(cwd) return project_files endfunction "}}} " This function looks to which project current buffer belongs. " {{{ GetProjectScript(project_files) " a:project_files = FindProjectScripts() function! GetProjectScript(project_files) for pfile in a:project_files if g:atp_debugLPS echomsg "Checking " . pfile endif let save_loclist = getloclist(0) let file_name = s:windows ? escape(expand("%:p"), '\') : escape(expand("%:p"), '/') let sfile_name = expand("%:t") try if !g:atp_RelativePath exe 'lvimgrep /^\s*let\s\+\%(b:atp_MainFile\s\+=\s*\%(''\|"\)\%(' . file_name . '\|' . sfile_name . '\)\>\%(''\|"\)\|b:ListOfFiles\s\+=.*\%(''\|"\)' . file_name . '\>\)/j ' . fnameescape(pfile) else exe 'lvimgrep /^\s*let\s\+\%(b:atp_MainFile\s\+=\s*\%(''\|"\)[^''"]*\<\%(' . sfile_name . '\)\>\%(''\|"\)\|b:ListOfFiles\s\+=.*\%(''\|"\)[^''"]*\<' . sfile_name . '\>\)/j ' . fnameescape(pfile) endif catch /E480:/ if g:atp_debugProject silent echomsg "Script file " . pfile . " doesn't match." endif endtry let loclist = getloclist(0) if len(loclist) let bufnr = get(get(loclist, 0, {}), 'bufnr', 'no match') if bufnr != 'no match' let project_script = fnamemodify(bufname(bufnr), ":p") endif return project_script " break endif endfor return "no project script found" endfunction "}}} " This function uses all three above functions: FindProjectScripts(), " GetProjectScript() and LoadScript() " {{{ LoadProjectScript " Note: bang has a meaning only for loading the common project script. function! LoadProjectScript(bang,...) if ( exists("g:atp_ProjectScript") && !g:atp_ProjectScript || exists("b:atp_ProjectScript") && ( !b:atp_ProjectScript && (!exists("g:atp_ProjectScript") || exists("g:atp_ProjectScript") && !g:atp_ProjectScript )) ) redir! >> /tmp/ATP_rs_debug silent echo "+++ SCIPING : LOAD PROJECT SCRIPT +++" redir END return endif let local = (a:0 >= 1 ? a:1 : 'local' ) if g:atp_debugLPS let time = reltime() endif if local == 'global' || local == 'common' call s:LoadScript(a:bang,s:common_project_script, 'global', 0, '', 1) if g:atp_debugLPS let g:LPS_time = reltimestr(reltime(time)) echomsg "LPS time (common): " . g:LPS_time endif return endif if !exists("b:atp_ProjectScriptFile") " Look for the project file " echo join(project_files, "\n") let project_files = FindProjectScripts() let g:project_files = project_files " Return if nothing was found if len(project_files) == 0 let b:atp_ProjectScriptFile = resolve(expand("%:p")) . ".project.vim" let b:atp_ProjectDir = fnamemodify(b:atp_ProjectScriptFile, ":h") return endif " Move project_file corresponding to the current buffer to the first " place if it exists. " This saves time :) when there are many project files " (especially when the projects are big) let index = index(project_files, expand("%:p") . ".project.vim") if index != -1 call remove(project_files, index) call extend(project_files, [ expand("%:p") . ".project.vim" ], 0) endif let save_loclist = getloclist(0) call setloclist(0, []) let project_script = GetProjectScript(project_files) if project_script != "no project script found" if g:atp_debugLPS echomsg "Loading " . project_script endif call LoadScript("", project_script, "local", 0, "silent", 1, 0) let b:atp_ProjectScriptFile = project_script let b:atp_ProjectDir = fnamemodify(b:atp_ProjectScriptFile, ":h") else " If there was no project script we set the variable and it will " be written when quiting vim by WriteProjectScript(). let b:atp_ProjectScriptFile = resolve(expand("%:p")) . ".project.vim" let b:atp_ProjectDir = fnamemodify(b:atp_ProjectScriptFile, ":h") return endif else try execute "silent! source " . fnameescape(b:atp_ProjectScriptFile) let b:atp_ProjectDir = fnamemodify(b:atp_ProjectScriptFile, ":h") catch /E484/ " this is used by the s:Babel() function. " if b:atp_ProjectDir is unset it returns. unlet b:atp_ProjectDir endtry endif if g:atp_debugLPS let g:LPS_time = reltimestr(reltime(time)) echomsg "LPS time: " . g:LPS_time endif endfunction function! s:LocalCommonComp(ArgLead, CmdLine, CursorPos) return filter([ 'local', 'common'], 'v:val =~ "^" . a:ArgLead') endfunction " }}} "}}} " Write Project Script: "{{{ s:WriteProjectScript(), :WriteProjectScript, autocommands " This function writes the project file but only if there there are changes. " This is so, because writing very long lines is much slower than reading (it " reads the file and compare the variables with the existing ones). try function! WriteProjectScript(bang, project_script, cached_variables, type) if g:atp_debugProject let g:project_script = a:project_script let g:type = a:type endif if g:atp_debugProject >= 2 let time = reltime() endif if !exists("b:ListOfFiles") let atp_MainFile = atplib#FullPath(b:atp_MainFile) call TreeOfFiles(atp_MainFile) endif if g:atp_debugProject echomsg "\n" redir! >> /tmp/ATP_ProjectScriptDebug.vim echomsg "ATP_ProjectScript: WriteProjectScript " . a:type let time = reltime() endif " If none of the variables exists -> return let exists=max(map(deepcopy(a:cached_variables), "exists(v:val)")) if !exists if g:atp_debugProject echomsg "no variable exists" endif if g:atp_debugProject >= 2 echomsg "time " . reltimestr(reltime(time)) endif return endif if a:bang == "" && expand("%:p") =~ 'texmf' if g:atp_debugProject echomsg "texmf return" endif if g:atp_debugProject let g:return = 1 endif if g:atp_debugProject >= 2 echomsg "time " . reltimestr(reltime(time)) endif return endif " a:bang == '!' then force to write project script even if it is turned off " localy or globaly. " The global variable overrides the local one! let cond = exists("g:atp_ProjectScript") && !g:atp_ProjectScript || exists("b:atp_ProjectScript") && ( !b:atp_ProjectScript && (!exists("g:atp_ProjectScript") || exists("g:atp_ProjectScript") && !g:atp_ProjectScript )) || !exists("b:atp_ProjectScript") && !exists("g:atp_ProjectScript") if a:bang == "" && cond echomsg "ATP WriteProjectScript: ProjectScript is turned off." if g:atp_debugProject redir END endif if g:atp_debugProject let g:return = 2 endif if g:atp_debugProject >= 2 echomsg "time " . reltimestr(reltime(time)) endif return endif let winsaveview = winsaveview() " Check if global variables where changed. " (1) copy global variable to l:variables " and remove defined global variables. " (2) source the project script and compare the results. " (3) resore variables and write the project script. if a:type == "global" let existing_variables = {} for var in a:cached_variables if g:atp_debugProject >= 2 echomsg var . " EXISTS " . exists(var) endif " step (1) copy variables let lvar = "l:" . substitute(var, '^[bg]:', '', '') if exists(var) call extend(existing_variables, { var : string({var}) }) exe "let " . lvar . "=" . string({var}) exe "unlet " . var " echomsg lvar . "=" . string({lvar}) endif endfor " step (2a) source project script if filereadable(a:project_script) execute "source " . fnameescape(a:project_script) endif let cond = 0 for var in a:cached_variables let lvar = "l:" . substitute(var, '^[bg]:', '', '') " step (2b) check if variables have changed if exists(var) && exists(lvar) let cond_A = ({lvar} != {var}) if g:atp_debugProject echomsg var . " and " . lvar . " exist. cond_A=" . cond_A endif let cond += cond_A if cond_A let {lvar} = {var} endif elseif !exists(var) && exists(lvar) if g:atp_debugProject echomsg var . " nexists but " . lvar . " exist." endif let {var} = {lvar} let cond += 1 elseif exists(var) && !exists(lvar) if g:atp_debugProject echomsg var . " exists and " . lvar . " nexist." endif unlet {var} let cond += 1 else if g:atp_debugProject echomsg var . " and " . lvar . " nexist." endif endif endfor if g:atp_debugProject let g:cond_global = cond echomsg "cond " . cond endif " step (3a) copy variables from local ones. for var in g:atp_cached_common_variables let lvar = "l:" . substitute(var, '^[bg]:', '', '') if g:atp_debugProject echomsg "(3a) " . var . " exists " . lvar . " " . ( exists(lvar) ? 'exists' : 'nexists' ) endif if exists(lvar) if g:atp_debugProject echomsg "(3a) Restoring " . var . " from " . lvar endif try let {var} = {lvar} catch /E741:/ exe "unlockvar " . var let {var} = {lvar} exe "lockvar " . var endtry endif endfor if cond == 0 if g:atp_debugProject silent echomsg "Project script not changed " . "\n" silent echo "time = " . reltimestr(reltime(time)) . "\n" endif if g:atp_debugProject let g:return = 3 endif if g:atp_debugProject >= 2 echomsg "time " . reltimestr(reltime(time)) endif return endif endif " Make a list of variables defined in project script let defined_variables = [] let save_loclist = getloclist(0) silent! exe 'lvimgrep /^\s*\\s\+[bg]:/j ' . fnameescape(a:project_script) let defined_variables = getloclist(0) call map(defined_variables, 'matchstr(v:val["text"], ''^\s*let\s\+\zs[bg]:[^[:blank:]=]*'')') call setloclist(0, save_loclist) if g:atp_debugProject let g:defined_variables = defined_variables endif let deleted_variables = [] for var in defined_variables if !exists(var) call add(deleted_variables, var) endif endfor if g:atp_debugProject let g:existing_variables = [] endif for var in a:cached_variables if exists(var) let lvar = 'l:' . substitute(var, '^[bg]:', '', '') let {lvar} = {var} if g:atp_debugProject call add(g:existing_variables, var) endif endif endfor if g:atp_debugProject let g:deleted_variables = deleted_variables endif let hidden = &l:hidden setl hidden let lazyredraw = &l:lazyredraw setl lazyredraw let bufnr = bufnr("%") try silent! exe "keepalt edit +setl\\ noswapfile " . fnameescape(a:project_script) catch /.*/ echoerr v:errmsg let errmsg = v:errmsg echoerr "WriteProjectScript catched error while opening " . a:project_script . ". Project script not written." let v:errmsg = errmsg let &l:hidden = hidden let &l:lazyredraw = lazyredraw if g:atp_debugProject let g:return = 4 endif if g:atp_debugProject >= 2 echomsg "time " . reltimestr(reltime(time)) endif return endtry if has("persistent_undo") setl noundofile endif " Delete the variables which where unlet: for var in deleted_variables try exe 'silent! %g/^\s*let\s\+' . var . '\>/d' catch /E48\%(6\|0\):/ endtry endfor " Write new variables: for var in a:cached_variables let lvar = "l:" . substitute(var, '^[bg]:', '', '') if g:atp_debugProject echomsg var . " " . exists(lvar) endif if exists(lvar) try exe 'silent! %g/^\s*let\s\+' . var . '\>/d' catch /E486:/ endtry call append('$', 'let ' . var . ' = ' . string({lvar})) endif endfor " Save project script file: silent w let projectscript_bufnr = bufnr("%") exe "silent keepalt b " . bufnr exe "bdelete " . projectscript_bufnr let &l:lazyredraw = lazyredraw call winrestview(winsaveview) if g:atp_debugProject silent echo "time = " . reltimestr(reltime(time)) redir END endif if g:atp_debugProject >= 2 echomsg "time " . reltimestr(reltime(time)) endif endfunction catch /E127:/ endtry function! WriteProjectScriptInterface(bang,...) let type = ( a:0 >= 1 ? a:1 : 'local' ) if type != 'global' && type != 'local' echoerr "WriteProjectScript Error : type can be: local or global." return endif let script = ( type == 'local' ? b:atp_ProjectScriptFile : s:common_project_script ) let variables = ( type == 'local' ? g:atp_cached_local_variables : g:atp_cached_common_variables ) if type == 'local' echomsg "Writing to " . b:atp_ProjectScriptFile endif call s:WriteProjectScript(a:bang, script, variables, type) endfunction function! s:WPSI_comp(ArgLead, CmdLine, CursorPos) return filter(['local', 'global'], 'v:val =~ a:ArgLead') endfunction "{{{ WriteProjectScript autocommands augroup ATP_WriteProjectScript au! " Before it was VimLeave au BufWrite *.tex call s:WriteProjectScript("", b:atp_ProjectScriptFile, g:atp_cached_local_variables, 'local') au BufWrite *.tex call s:WriteProjectScript("", s:common_project_script, g:atp_cached_common_variables, 'global') augroup END "}}} "}}} " Set Project Script: on/off " {{{ s:ProjectScript function! ProjectScript(...) let arg = ( a:0 >=1 ? a:1 : "" ) if arg == "" let b:atp_ProjectScript=!b:atp_ProjectScript elseif arg == "on" let b:atp_ProjectScript=1 :WriteProjectScript! elseif arg == "off" let b:atp_ProjectScript=0 :WriteProjectScript! endif if b:atp_ProjectScript echomsg "Project Script is set on." else echomsg "Project Script is set off." endif return b:atp_ProjectScript endfunction function! HistComp(ArgLead, CmdLine, CursorPos) return filter(['on', 'off'], 'v:val =~ a:ArgLead') endfunction "}}} " Delete Project Script: " s:DeleteProjectScript {{{ " It has one argument a:1 == "local" or " a:0 == 0 " delete the " b:atp_ProjectScriptFile. " otherwise delete s:common_project_script. With bang it forces to delete the " s:common_project_script" " It also unlets the variables stored in s:common_project_script. function! DeleteProjectScript(bang,...) let type = ( a:0 >= 1 ? a:1 : "local" ) if type == "local" let file = b:atp_ProjectScriptFile else let file = s:common_project_script endif call delete(file) echo "Project Script " . file . " deleted." if type == "local" && a:bang == "!" let file = s:common_project_script call delete(file) echo "Project Script " . file . " deleted." endif if file == s:common_project_script for var in g:atp_cached_common_variables exe "unlet " . var endfor endif endfunction function! s:DelPS(CmdArg, CmdLine, CursorPos) let comp = [ "local", "common" ] call filter(comp, "v:val =~ '^' . a:CmdArg") return comp endfunction " Show ProjectScript: " function! ShowProjectScript(bang) " " let history_file " endfunction " }}} endif "}}} " The Script: " (includes commands, and maps - all the things " that must be sources for each file) " {{{ call LoadProjectScript("", "local") " Project script should by loaded now, and not by autocommands which are executed after " sourcing scripts. In this way variables set in project script will be used " when sourcing other atp scripts. call s:LoadScript("", s:common_project_script, 'global', 0, 'silent',1) " Commands: command! -buffer -bang -nargs=? -complete=customlist,s:LocalCommonGlobalComp LoadProjectScript :call LoadProjectScript(,) " write: command! -buffer -bang -nargs=? -complete=customlist,s:WPSI_comp WriteProjectScript :call WriteProjectScriptInterface(,) command! -buffer -nargs=* -complete=customlist,HistComp ProjectScript :call ProjectScript() " delete: command! -buffer -bang -complete=customlist,s:DelPS -nargs=? DeleteProjectScript :call s:DeleteProjectScript(, ) " }}} ftplugin/ATP_files/common.vim [[[1 743 " Author: Marcin Szamotulski " Description: This script has functions which have to be called before ATP_files/options.vim " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " Language: tex " This file contains set of functions which are needed to set to set the atp " options and some common tools. let s:sourced = exists("s:sourced") ? 1 : 0 if !exists("g:atp_reload") let g:atp_reload = 0 endif " {{{ Variables if !exists("g:askfortheoutdir") || g:atp_reload let g:askfortheoutdir = 0 endif if !exists("g:atp_raw_texinputs") let g:atp_raw_texinputs = substitute(substitute(substitute(system("kpsewhich -show-path tex"),'!!','','g'),'\/\/\+','\/','g'), ':\|\n', ',', 'g') " lockvar g:atp_raw_texinputs endif " atp tex and bib inputs directories (kpsewhich) if !exists("g:atp_texinputs") || g:atp_reload let path_list = split(g:atp_raw_texinputs, ',') let idx = index(path_list, '.') if idx != -1 let dot = remove(path_list, index(path_list,'.')) . "," else let dot = "" endif call map(path_list, 'v:val . "**"') let g:atp_texinputs = dot . join(path_list, ',') endif " a list where tex looks for bib files " It must be defined before SetProjectName function. if !exists("g:atp_raw_bibinputs") || g:atp_reload let g:atp_raw_bibinputs=substitute(substitute(substitute( \ system("kpsewhich -show-path bib"), \ '\/\/\+', '\/', 'g'), \ '!\|\n', '', 'g'), \ ':', ',' , 'g') endif if !exists("g:atp_bibinputs") || g:atp_reload let path_list = split(g:atp_raw_bibinputs, ',') let idx = index(path_list, '.') if idx != -1 let dot = remove(path_list, index(path_list,'.')) . "," else let dot = "" endif call map(path_list, 'v:val . "**"') let g:atp_bibinputs = dot . join(path_list, ',') endif " }}} " Functions: (source once) if !s:sourced || g:atp_reload_functions "{{{ " Set the project name "{{{ SetProjectName (function and autocommands) " This function sets the main project name (b:atp_MainFile) " " It is used by EditInputFile which copies the value of this variable to every " input file included in the main source file. " " nmap gf (GotoFile function) is not using this function. " " the b:atp_MainFile variable is set earlier in the startup " (by the augroup ATP_Syntax_TikzZone), calling SetProjectName to earlier cause " problems (g:atp_raw_bibinputs undefined). " " ToDo: CHECK IF THIS IS WORKS RECURSIVELY? " ToDo: THIS FUNCTION SHUOLD NOT SET AUTOCOMMANDS FOR AuTeX function! " every tex file should be compiled (the compiler function calls the " right file to compile! " " {{{ SetProjectName ( function ) " store a list of all input files associated to some file function! SetProjectName(...) let bang = ( a:0 >= 1 ? a:1 : "" ) " do we override b:atp_project let did = ( a:0 >= 2 ? a:2 : 1 ) " do we check if the project name was set " but also overrides the current b:atp_MainFile when 0 " if the project name was already set do not set it for the second time " (which sets then b:atp_MainFile to wrong value!) if &filetype == "fd_atp" " this is needed for EditInputFile function to come back to the main " file. let b:atp_MainFile = ( g:atp_RelativePath ? expand("%:t") : expand("%:p") ) let b:did_project_name = 1 endif if exists("b:did_project_name") && b:did_project_name && did return " project name was already set" else let b:did_project_name = 1 endif if !exists("b:atp_project") || bang == "!" let b:atp_MainFile = exists("b:atp_MainFile") && did ? b:atp_MainFile : ( g:atp_RelativePath ? expand("%:t") : expand("%:p") ) " let b:atp_ProjectDir = fnamemodify(resolve(b:atp_MainFile), ":h") let pn_return = " set from history or just set to " . b:atp_MainFile . " exists=" . exists("b:atp_MainFile") . " did=" . did elseif exists("b:atp_project") let b:atp_MainFile = ( g:atp_RelativePath ? fnamemodify(b:atp_project, ":t") : b:atp_project ) " let b:atp_ProjectDir = fnamemodify(resolve(b:atp_MainFile), ":h") let pn_return = " set from b:atp_project to " . b:atp_MainFile endif " we need to escape white spaces in b:atp_MainFile but not in all places so " this is not done here " Now we can run things that needs the project name: if !exists("b:atp_PackageList") let b:atp_PackageList = atplib#GrepPackageList() endif if !exists("b:atp_ProjectDir") let b:atp_ProjectDir = ( exists("b:atp_ProjectScriptFile") ? fnamemodify(b:atp_ProjectScriptFile, ":h") : fnamemodify(resolve(expand("%:p")), ":h") ) endif return pn_return endfunction " }}} " if !s:sourced " augroup ATP_SetProjectName " au BufEnter *.tex :call SetProjectName() " au BufEnter *.fd :call SetProjectName() " augroup END " endif "}}} " This functions sets the value of b:atp_OutDir variable " {{{ s:SetOutDir " This options are set also when editing .cls files. " It can overwrite the value of b:atp_OutDir " if arg != 0 then set errorfile option accordingly to b:atp_OutDir " if a:0 >0 0 then b:atp_atp_OutDir is set iff it doesn't exsits. function! s:SetOutDir(arg, ...) " THIS FUNCTION SHOULD BE REVIEWED !!! if exists("b:atp_OutDir") && a:0 >= 1 return "atp_OutDir EXISTS" endif " first we have to check if this is not a project file if exists("b:atp_project") || exists("s:inputfiles") && \ ( index(keys(s:inputfiles),fnamemodify(bufname("%"),":t:r")) != '-1' || \ index(keys(s:inputfiles),fnamemodify(bufname("%"),":t")) != '-1' ) " if we are in a project input/include file take the correct value of b:atp_OutDir from the atplib#s:outdir_dict dictionary. if index(keys(s:inputfiles),fnamemodify(bufname("%"),":t:r")) != '-1' let b:atp_OutDir=substitute(g:outdir_dict[s:inputfiles[fnamemodify(bufname("%"),":t:r")][1]], '\\\s', ' ', 'g') elseif index(keys(s:inputfiles),fnamemodify(bufname("%"),":t")) != '-1' let b:atp_OutDir=substitute(g:outdir_dict[s:inputfiles[fnamemodify(bufname("%"),":t")][1]], '\\\s', ' ', 'g') endif else " if we are not in a project input/include file set the b:atp_OutDir " variable " if the user want to be asked for b:atp_OutDir if g:askfortheoutdir == 1 let b:atp_OutDir=substitute(input("Where to put output? do not escape white spaces "), '\\\s', ' ', 'g') endif if ( get(getbufvar(bufname("%"),""),"outdir","optionnotset") == "optionnotset" \ && g:askfortheoutdir != 1 \ || b:atp_OutDir == "" && g:askfortheoutdir == 1 ) \ && !exists("$TEXMFOUTPUT") let b:atp_OutDir=substitute(fnamemodify(resolve(expand("%:p")),":h") . "/", '\\\s', ' ', 'g') " echomsg "Output Directory ".b:atp_OutDir elseif exists("$TEXMFOUTPUT") let b:atp_OutDir=substitute($TEXMFOUTPUT, '\\\s', ' ', 'g') endif " if arg != 0 then set errorfile option accordingly to b:atp_OutDir if bufname("") =~ ".tex$" && a:arg != 0 call s:SetErrorFile() endif if exists("g:outdir_dict") let g:outdir_dict = extend(g:outdir_dict, {fnamemodify(bufname("%"),":p") : b:atp_OutDir }) else let g:outdir_dict = { fnamemodify(bufname("%"),":p") : b:atp_OutDir } endif endif return b:atp_OutDir endfunction " }}} " This function sets vim 'errorfile' option. " {{{ s:SetErrorFile (function and autocommands) " let &l:errorfile=b:atp_OutDir . fnameescape(fnamemodify(expand("%"),":t:r")) . ".log" "{{{ s:SetErrorFile function! s:SetErrorFile() " set b:atp_OutDir if it is not set if !exists("b:atp_OutDir") call s:SetOutDir(0) endif " set the b:atp_MainFile varibale if it is not set (the project name) if !exists("b:atp_MainFile") call SetProjectName() endif let atp_MainFile = atplib#FullPath(b:atp_MainFile) " vim doesn't like escaped spaces in file names ( cg, filereadable(), " writefile(), readfile() - all acepts a non-escaped white spaces) if has("win16") || has("win32") || has("win64") || has("win95") let errorfile = substitute(atplib#append(b:atp_OutDir, '\') . fnamemodify(atp_MainFile,":t:r") . ".log", '\\\s', ' ', 'g') else let errorfile = substitute(atplib#append(b:atp_OutDir, '/') . fnamemodify(atp_MainFile,":t:r") . ".log", '\\\s', ' ', 'g') endif let &l:errorfile = errorfile return &l:errorfile endfunction command! -buffer SetErrorFile :call s:SetErrorFile() "}}} " if !s:sourced augroup ATP_SetErrorFile au BufEnter *.tex call SetErrorFile() au BufRead $l:errorfile setlocal autoread augroup END " endif "}}} " Make a tree of input files. " {{{ TreeOfFiles " this is needed to make backward searching. " It returns: " [ {tree}, {list} , {type_dict}, {level_dict} ] " where {tree}: " is a tree of files of the form " { file : [ subtree, linenr ] } " where the linenr is the linenr of \input{file} iline the one level up " file. " {list}: " is just list of all found input files. " {type_dict}: " is a dictionary of types for files in {list} " type is one of: preambule, input, bib. " " {flat} = 1 do not be recursive " {flat} = 0 the deflaut be recursive for input files (not bib and not preambule) " bib and preambule files are not added to the tree " {flat} = -1 include input and premabule files into the tree " " TreeOfFiles({main_file}, [{pattern}, {flat}, {run_nr}]) " debug file - /tmp/tof_log " a:main_file is the main file to start with function! TreeOfFiles(main_file,...) " let time = reltime() let atp_MainFile = atplib#FullPath(b:atp_MainFile) if !exists("b:atp_OutDir") call s:SetOutDir(0, 1) endif let tree = {} " flat = do a flat search, i.e. fo not search in input files at all. let flat = a:0 >= 2 ? a:2 : 0 " This prevents from long runs on package files " for example babel.sty has lots of input files. if expand("%:e") != 'tex' redir END return [ {}, [], {}, {} ] endif let run_nr = a:0 >= 3 ? a:3 : 1 let pattern = a:0 >= 1 ? a:1 : g:atp_inputfile_pattern if run_nr == 1 && '\subfile{' !~ g:atp_inputfile_pattern && atplib#SearchPackage('subfiles') let g:atp_inputfile_pattern = '^[^%]*\\\(input\s*{\=\|include\s*{\|bibliography\s*{\|subfile\s*{\)' endif if g:atp_debugToF if run_nr == 1 redir! > /tmp/tof_log else redir! >> /tmp/tof_log endif endif if g:atp_debugToF silent echo run_nr . ") |".a:main_file."| expand=".expand("%:p") endif if run_nr == 1 let cwd = getcwd() exe "lcd " . fnameescape(b:atp_ProjectDir) endif let line_nr = 1 let ifiles = [] let list = [] let type_dict = {} let level_dict = {} let saved_llist = getloclist(0) if run_nr == 1 && &l:filetype =~ '^\(ams\)\=tex$' try silent execute 'lvimgrep /\\begin\s*{\s*document\s*}/j ' . fnameescape(a:main_file) catch /E480:/ endtry let end_preamb = get(get(getloclist(0), 0, {}), 'lnum', 0) else let end_preamb = 0 endif try silent execute "lvimgrep /".pattern."/jg " . fnameescape(a:main_file) catch /E480:/ catch /E683:/ " let g:pattern = pattern " let g:filename = fnameescape(a:main_file) endtry let loclist = getloclist(0) call setloclist(0, saved_llist) let lines = map(loclist, "[ v:val['text'], v:val['lnum'], v:val['col'] ]") if g:atp_debugToF silent echo run_nr . ") Lines: " .string(lines) endif for entry in lines let [ line, lnum, cnum ] = entry " input name (iname) as appeared in the source file let iname = substitute(matchstr(line, pattern . '\(''\|"\)\=\zs\f\%(\f\|\s\)*\ze\1\='), '\s*$', '', '') if g:atp_debugToF silent echo run_nr . ") iname=".iname endif if line =~ '{\s*' . iname let iname = substitute(iname, '\\\@> /tmp/tof_log silent! echo "========TreeOfFiles========================" silent! echo "TreeOfFiles b:ListOfFiles=" . string(b:ListOfFiles) redir END endif return [ tree, list, type_dict, level_dict ] endfunction "}}} " This function finds all the input and bibliography files declared in the source files (recursive). " {{{ FindInputFiles " Returns a dictionary: " { : [ 'bib', 'main file', 'full path' ] } " with the same format as the output of FindInputFiles " a:MainFile - main file (b:atp_MainFile) " a:1 = 0 [1] - use cached values of tree of files. function! FindInputFiles(MainFile,...) let cached_Tree = a:0 >= 1 ? a:1 : 0 let saved_llist = getloclist(0) call setloclist(0, []) if cached_Tree && exists("b:TreeOfFiles") let [ TreeOfFiles, ListOfFiles, DictOfFiles, LevelDict ]= deepcopy([ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ]) else if &filetype == "plaintex" let flat = 1 else let flat = 0 endif let [ TreeOfFiles, ListOfFiles, DictOfFiles, LevelDict ]= TreeOfFiles(fnamemodify(a:MainFile, ":p"), g:atp_inputfile_pattern, flat) " Update the cached values: let [ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ] = deepcopy([ TreeOfFiles, ListOfFiles, DictOfFiles, LevelDict ]) endif let AllInputFiles = keys(filter(copy(DictOfFiles), " v:val == 'input' || v:val == 'preambule' ")) let AllBibFiles = keys(filter(copy(DictOfFiles), " v:val == 'bib' ")) let b:AllInputFiles = deepcopy(AllInputFiles) let b:AllBibFiles = deepcopy(AllBibFiles) " this variable will store unreadable bibfiles: let NotReadableInputFiles=[] " this variable will store the final result: let Files = {} for File in ListOfFiles let File_Path = atplib#FullPath(File) if filereadable(File) call extend(Files, \ { fnamemodify(File_Path,":t:r") : [ DictOfFiles[File] , fnamemodify(a:MainFile, ":p"), File_Path ] }) else " echo warning if a bibfile is not readable " echohl WarningMsg | echomsg "File " . File . " not found." | echohl None if count(NotReadableInputFiles, File_Path) == 0 call add(NotReadableInputFiles, File_Path) endif endif endfor let g:NotReadableInputFiles = NotReadableInputFiles " return the list of readable bibfiles return Files endfunction function! UpdateMainFile() if b:atp_MainFile =~ '^\s*\/' let cwd = getcwd() exe "lcd " . fnameescape(b:atp_ProjectDir) let b:atp_MainFile = ( g:atp_RelativePath ? fnamemodify(b:atp_MainFile, ":.") : b:atp_MainFile ) exe "lcd " . fnameescape(cwd) else let b:atp_MainFile = ( g:atp_RelativePath ? b:atp_MainFile : atplib#FullPath(b:atp_MainFile) ) endif return endfunction "}}} " All Status Line related things: "{{{ Status Line function! s:StatusOutDir() "{{{ let status="" if exists("b:atp_OutDir") if b:atp_OutDir != "" let status= status . "Output dir: " . pathshorten(substitute(b:atp_OutDir,"\/\s*$","","")) else let status= status . "Please set the Output directory, b:atp_OutDir" endif endif return status endfunction "}}} " There is a copy of this variable in compiler.vim function! ATPRunning() "{{{ if exists("b:atp_running") && exists("g:atp_callback") && b:atp_running && g:atp_callback " let b:atp_running = b:atp_running < 0 ? 0 : b:atp_running " redrawstatus for cmd in keys(g:CompilerMsg_Dict) if b:atp_TexCompiler =~ '^\s*' . cmd . '\s*$' let Compiler = g:CompilerMsg_Dict[cmd] break else let Compiler = b:atp_TexCompiler endif endfor if b:atp_running >= 2 return b:atp_running." ".Compiler." " elseif b:atp_running >= 1 return Compiler." " else return "" endif endif return '' endfunction "}}} " {{{ Syntax and Hilighting " ToDo: " syntax match atp_statustitle /.*/ " syntax match atp_statussection /.*/ " syntax match atp_statusoutdir /.*/ " hi link atp_statustitle Number " hi link atp_statussection Title " hi link atp_statusoutdir String " }}} function! s:SetNotificationColor() "{{{ " use the value of the variable g:atp_notification_{g:colors_name}_guibg " if it doesn't exists use the default value (the same as the value of StatusLine " (it handles also the reverse option!) let colors_name = exists("g:colors_name") ? g:colors_name : "default" " let g:cname = colors_name " Note: the names of variable uses gui but equally well it could be cterm. As " they work in gui and vim. if has("gui_running") let notification_guibg = exists("g:atp_notification_".colors_name."_guibg") ? \ g:atp_notification_{colors_name}_guibg : \ ( synIDattr(synIDtrans(hlID("StatusLine")), "reverse") ? \ synIDattr(synIDtrans(hlID("StatusLine")), "fg#") : \ synIDattr(synIDtrans(hlID("StatusLine")), "bg#") ) let notification_guifg = exists("g:atp_notification_".colors_name."_guifg") ? \ g:atp_notification_{colors_name}_guifg : \ ( synIDattr(synIDtrans(hlID("StatusLine")), "reverse") ? \ synIDattr(synIDtrans(hlID("StatusLine")), "bg#") : \ synIDattr(synIDtrans(hlID("StatusLine")), "fg#") ) let notification_gui = exists("g:atp_notification_".colors_name."_gui") ? \ g:atp_notification_{colors_name}_gui : \ ( (synIDattr(synIDtrans(hlID("StatusLine")), "bold") ? "bold" : "" ) . \ (synIDattr(synIDtrans(hlID("StatusLine")), "underline") ? ",underline" : "" ) . \ (synIDattr(synIDtrans(hlID("StatusLine")), "underculr") ? ",undercurl" : "" ) . \ (synIDattr(synIDtrans(hlID("StatusLine")), "italic") ? ",italic" : "" ) ) else let notification_guibg = exists("g:atp_notification_".colors_name."_ctermbg") ? \ g:atp_notification_{colors_name}_ctermbg : \ ( synIDattr(synIDtrans(hlID("StatusLine")), "reverse") ? \ synIDattr(synIDtrans(hlID("StatusLine")), "fg#") : \ synIDattr(synIDtrans(hlID("StatusLine")), "bg#") ) let notification_guifg = exists("g:atp_notification_".colors_name."_ctermfg") ? \ g:atp_notification_{colors_name}_ctermfg : \ ( synIDattr(synIDtrans(hlID("StatusLine")), "reverse") ? \ synIDattr(synIDtrans(hlID("StatusLine")), "bg#") : \ synIDattr(synIDtrans(hlID("StatusLine")), "fg#") ) let notification_gui = exists("g:atp_notification_".colors_name."_cterm") ? \ g:atp_notification_{colors_name}_cterm : \ ( (synIDattr(synIDtrans(hlID("StatusLine")), "bold") ? "bold" : "" ) . \ (synIDattr(synIDtrans(hlID("StatusLine")), "underline") ? ",underline" : "" ) . \ (synIDattr(synIDtrans(hlID("StatusLine")), "underculr") ? ",undercurl" : "" ) . \ (synIDattr(synIDtrans(hlID("StatusLine")), "italic") ? ",italic" : "" ) ) endif if has("gui_running") let g:notification_gui = notification_gui let g:notification_guibg = notification_guibg let g:notification_guifg = notification_guifg else let g:notification_cterm = notification_gui let g:notification_ctermbg = notification_guibg let g:notification_ctermfg = notification_guifg endif if has("gui_running") let prefix = "gui" else let prefix = "cterm" endif let hi_gui = ( notification_gui != "" && notification_gui != -1 ? " ".prefix."=" . notification_gui : "" ) let hi_guifg = ( notification_guifg != "" && notification_guifg != -1 ? " ".prefix."fg=" . notification_guifg : "" ) let hi_guibg = ( notification_guibg != "" && notification_guibg != -1 ? " ".prefix."bg=" . notification_guibg : "" ) if (notification_gui == -1 || notification_guifg == -1 || notification_guibg == -1) return endif " Highlight command: try execute "hi User".g:atp_statusNotifHi ." ". hi_gui . hi_guifg . hi_guibg catch /E418:/ endtry endfunction "}}} " The main status function, it is called via autocommand defined in 'options.vim'. let s:errormsg = 0 function! ATPStatus(bang) "{{{ let g:status_OutDir = a:bang == "" && g:atp_statusOutDir || a:bang == "!" && !g:atp_statusOutDir ? s:StatusOutDir() : "" let status_CTOC = &filetype =~ '^\(ams\)\=tex' ? CTOC("return") : '' if g:atp_statusNotifHi > 9 || g:atp_statusNotifHi < 0 let g:atp_statusNotifHi = 9 if !s:errormsg echoerr "Wrong value of g:atp_statusNotifHi, should be 0,1,...,9. Setting it to 9." let s:errormsg = 1 endif endif let status_NotifHi = \ ( g:atp_statusNotif && g:atp_statusNotifHi ? '%#User'.g:atp_statusNotifHi . '#' : '' ) let status_NotifHiPost = \ ( g:atp_statusNotif && g:atp_statusNotifHi ? '%#StatusLine#' : '' ) let status_Notif = ( g:atp_statusNotif ? '%{ATPRunning()}' : '' ) let status_KeyMap = ( has("keymap") && g:atp_babel && exists("b:keymap_name") \ ? b:keymap_name : '' ) let g:atp_StatusLine= '%<%f '.status_KeyMap.'%(%h%m%r%) %='.status_CTOC." ".status_NotifHi.status_Notif.status_NotifHiPost.'%{g:status_OutDir} %-14.16(%l,%c%V%)%P' set statusline=%!g:atp_StatusLine endfunction try command -buffer -bang Status :call ATPStatus() catch /E174:/ command! -buffer -bang ATPStatus :call ATPStatus() endtry " }}} "}}} endif "}}} " The Script: " (includes commands, and maps - all the things " that must be sources for each file " + sets g:atp_inputfile_pattern variable) " {{{ call SetProjectName() " The pattern g:atp_inputfile_pattern should match till the begining of the file name " and shouldn't use \zs:\ze. if !exists("g:atp_inputfile_pattern") || g:atp_reload if &filetype == 'plaintex' let g:atp_inputfile_pattern = '^[^%]*\\input\s*' else if atplib#SearchPackage("subfiles") let g:atp_inputfile_pattern = '^[^%]*\\\(input\s*{\=\|include\s*{\|bibliography\s*{\|subfile\s*{\)' else let g:atp_inputfile_pattern = '^[^%]*\\\(input\s*{\=\|include\s*{\|bibliography\s*{\)' endif endif endif call s:SetOutDir(0, 1) if expand("%:e") == "tex" " cls and sty files also have filetype 'tex', this prevents from setting the error " file for them. call s:SetErrorFile() endif command! -buffer -bang SetProjectName :call SetProjectName(, 0) command! -buffer SetOutDir :call SetOutDir(1) command! -buffer InputFiles :call UpdateMainFile() | :call FindInputFiles(atplib#FullPath(b:atp_MainFile)) | echo join([b:atp_MainFile]+b:ListOfFiles, "\n") " This should set the variables and run s:SetNotificationColor function command! -buffer SetNotificationColor :call s:SetNotificationColor() augroup ATP_SetStatusLineNotificationColor au! au BufEnter *tex :call s:SetNotificationColor() au ColorScheme * :call s:SetNotificationColor() augroup END "}}} " vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1 ftplugin/ATP_files/compiler.vim [[[1 1577 " Author: Marcin Szamotulski " Note: this file contain the main compiler function and related tools, to " view the output, see error file. " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " Language: tex " Last Change: " Some options (functions) should be set once: let s:sourced = exists("s:sourced") ? 1 : 0 " Functions: (source once) if !s:sourced || g:atp_reload_functions "{{{ " Internal Variables " {{{ " This limits how many consecutive runs there can be maximally. let s:runlimit = 9 let s:texinteraction = "nonstopmode" compiler tex " }}} " This is the function to view output. It calls compiler if the output is a not " readable file. " {{{ ViewOutput " a:1 == "RevSearch" if run from RevSearch() function and the output file doesn't " exsists call compiler and RevSearch(). function! ViewOutput(...) let atp_MainFile = atplib#FullPath(b:atp_MainFile) let fwd_search = ( a:0 == 1 && a:1 =~? 'sync' ? 1 : 0 ) call atplib#outdir() " Set the correct output extension (if nothing matches set the default '.pdf') let ext = get(g:atp_CompilersDict, matchstr(b:atp_TexCompiler, '^\s*\zs\S\+\ze'), ".pdf") " Read the global options from g:atp_{b:atp_Viewer}Options variables let global_options = exists("g:atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") ? g:atp_{matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')}Options : "" let local_options = getbufvar(bufnr("%"), "atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") " let g:options = global_options ." ". local_options " Follow the symbolic link let link=system("readlink " . shellescape(atp_MainFile)) if link != "" let outfile = fnamemodify(link,":r") . ext else let outfile = fnamemodify(atp_MainFile,":r"). ext endif if b:atp_Viewer == "xpdf" let viewer = b:atp_Viewer . " -remote " . shellescape(b:atp_XpdfServer) else let viewer = b:atp_Viewer endif let sync_args = ( fwd_search ? SyncTex(0,1) : "" ) let g:global_options = global_options let g:local_options = local_options let g:sync_args = sync_args let g:viewer = viewer if b:atp_Viewer =~ '\' && fwd_search let view_cmd = "(".viewer." ".global_options." ".local_options." ".sync_args.")&" elseif b:atp_Viewer =~ '^\s*xdvi\>' let view_cmd = "(".viewer." ".global_options." ".local_options." ".sync_args." ".shellescape(outfile).")&" else " I couldn't get it work with okular. " let SyncTex = s:SidWrap('SyncTex') " let sync_cmd = (fwd_search ? "vim "." --servername ".v:servername." --remote-expr "."'".SyncTex."()';" : "" ) " let g:sync_cmd=sync_cmd let view_cmd = viewer." ".global_options." ".local_options." ".shellescape(outfile)."&" endif if g:atp_debugV let g:view_cmd = view_cmd endif if filereadable(outfile) let g:debug=0 if b:atp_Viewer == "xpdf" call system(view_cmd) else call system(view_cmd) redraw! endif else let g:debug=1 echomsg "Output file do not exists. Calling " . b:atp_TexCompiler if fwd_search call s:Compiler( 0, 2, 1, 'silent' , "AU" , atp_MainFile, "") else call s:Compiler( 0, 1, 1, 'silent' , "AU" , atp_MainFile, "") endif endif endfunction noremap ATP_ViewOutput :call ViewOutput() "}}} " Forward Search function! GetSyncData(line, col) if !filereadable(fnamemodify(atplib#FullPath(b:atp_MainFile), ":r").'.synctex.gz') echomsg "Calling ".get(g:CompilerMsg_Dict, b:atp_TexCompiler, b:atp_TexCompiler)." to generate synctex data. Wait a moment..." call system(b:atp_TexCompiler . " -synctex=1 " . b:atp_MainFile) endif " Note: synctex view -i line:col:tex_file -o output_file " tex_file must be full path. let synctex_cmd="synctex view -i ".a:line.":".a:col.":'".fnamemodify(b:atp_MainFile, ":p"). "' -o '".fnamemodify(b:atp_MainFile, ":p:r").".pdf'" let synctex_output=split(system(synctex_cmd), "\n") if get(synctex_output, 1, '') =~ '^SyncTex Warning:' return [ "no_sync", get(synctex_output, 1, '') ] endif if g:atp_debugSync let g:synctex_cmd=synctex_cmd let g:synctex_ouput=copy(synctex_output) endif let page_list=copy(synctex_output) call filter(page_list, "v:val =~ '^\\cpage:\\d\\+'") let page=get(page_list, 0, "no_sync") let y_coord_list=copy(synctex_output) call filter(y_coord_list, "v:val =~ '^\\cy:\\d\\+'") let y_coord=matchstr(get(y_coord_list, 0, "no sync data"), 'y:\zs[0-9.]*') if g:atp_debugSync let g:page=page let g:y_coord=y_coord endif if page == "no_sync" return [ "no_sync", "No SyncTex Data: try on another line (comments are not allowed)." ] endif let page_nr=matchstr(page, '^\cPage:\zs\d\+') return [ page_nr, y_coord ] endfunction function! SyncShow( page_nr, y_coord) if a:y_coord < 325 let height="Top" elseif a:y_coord < 550 let height="Middle" else let height="Bottom" endif if a:page_nr != "no_sync" echomsg height." of page ".a:page_nr else echohl WarningMsg echomsg a:y_coord " echomsg "You cannot forward search on comment lines, if this is not the case try one or two lines above/below" echohl Normal endif endfunction function! SyncTex(mouse, ...) "{{{ let dryrun = ( a:0 >= 2 && a:2 == 1 ? 1 : 0 ) let output_check = ( a:0 >= 1 && a:1 == 0 ? 0 : 1 ) let [ line, col ] = ( a:mouse ? [ v:mouse_lnum, v:mouse_col ] : [ line("."), col(".") ] ) echomsg "Lint=" . line let atp_MainFile = atplib#FullPath(b:atp_MainFile) let ext = get(g:atp_CompilersDict, matchstr(b:atp_TexCompiler, '^\s*\zs\S\+\ze'), ".pdf") let output_file = fnamemodify(atp_MainFile,":p:r") . ext if !filereadable(output_file) && output_check ViewOutput sync return 2 endif if b:atp_Viewer == "xpdf" let [ page_nr, y_coord ] = GetSyncData(line, col) let sync_cmd = "xpdf -remote " . shellescape(b:atp_XpdfServer) . ' -exec gotoPage\('.page_nr.'\)' let sync_args = sync_cmd if !dryrun call system(sync_cmd) call SyncShow(page_nr, y_coord) endif elseif b:atp_Viewer == "okular" let [ page_nr, y_coord ] = GetSyncData(line, col) " This will not work in project files. (so where it is mostly needed.) let sync_cmd = "okular --unique ".shellescape(expand("%:p:r")).".pdf\\#src:".line.shellescape(expand("%:p"))." &" let sync_args = " ".shellescape(expand("%:p:r")).".pdf\\#src:".line.shellescape(expand("%:p"))." " if !dryrun call system(sync_cmd) redraw! call SyncShow(page_nr, y_coord) endif " elseif b:atp_Viewer == "evince" " let rev_searchcmd="synctex view -i ".line(".").":".col(".").":".fnameescape(b:atp_MainFile). " -o ".fnameescape(fnamemodify(b:atp_MainFile, ":p:r").".pdf") . " -x 'evince %{output} -i %{page}'" " endif elseif b:atp_Viewer =~ '^\s*xdvi\>' let options = (exists("g:atp_xdviOptions") ? g:atp_xdviOptions : "" ) . getbufvar(bufnr(""), "atp_xdviOptions") let sync_cmd = "xdvi ".options. \ " -editor '".v:progname." --servername ".v:servername. \ " --remote-wait +%l %f' -sourceposition " . \ line.":".col.shellescape(fnameescape(fnamemodify(expand("%"),":p"))). \ " " . fnameescape(output_file) let sync_args = " -sourceposition ".line.":".col.shellescape(fnameescape(fnamemodify(expand("%"),":p")))." " if !dryrun call system(sync_cmd) endif else let sync_cmd="" endif let g:sync_cmd = sync_cmd return sync_args endfunction nmap SyncTexKeyStroke :call SyncTex(0) nmap SyncTexMouse :call SyncTex(1) "}}} " " This function gets the pid of the running compiler " ToDo: review LatexBox has a better approach! "{{{ Get PID Functions function! getpid() let s:command="ps -ef | grep -v " . $SHELL . " | grep " . b:atp_TexCompiler . " | grep -v grep | grep " . fnameescape(expand("%")) . " | awk 'BEGIN {ORS=\" \"} {print $2}'" let s:var = system(s:command) return s:var endfunction function! GetPID() let s:var=s:getpid() if s:var != "" echomsg b:atp_TexCompiler . " pid " . s:var else let b:atp_running = 0 echomsg b:atp_TexCompiler . " is not running" endif endfunction "}}} " To check if xpdf is running we use 'ps' unix program. "{{{ s:xpdfpid function! xpdfpid() let s:checkxpdf="ps -ef | grep -v grep | grep xpdf | grep '-remote '" . shellescape(b:atp_XpdfServer) . " | awk '{print $2}'" return substitute(system(s:checkxpdf),'\D','','') endfunction "}}} " This function compares two files: file written on the disk a:file and the current " buffer "{{{ s:compare " relevant variables: " g:atp_compare_embedded_comments " g:atp_compare_double_empty_lines " Problems: " This function is too slow it takes 0.35 sec on file with 2500 lines. " Ideas: " Maybe just compare current line! " (search for the current line in the written " file with vimgrep) function! compare(file) let l:buffer=getbufline(bufname("%"),"1","$") " rewrite l:buffer to remove all comments let l:buffer=filter(l:buffer, 'v:val !~ "^\s*%"') let l:i = 0 if g:atp_compare_double_empty_lines == 0 || g:atp_compare_embedded_comments == 0 while l:i < len(l:buffer)-1 let l:rem=0 " remove comment lines at the end of a line if g:atp_compare_embedded_comments == 0 let l:buffer[l:i] = substitute(l:buffer[l:i],'%.*$','','') endif " remove double empty lines (i.e. from two conecutive empty lines " the first one is deleted, the second remains), if the line was " removed we do not need to add 1 to l:i (this is the role of " l:rem). if g:atp_compare_double_empty_lines == 0 && l:i< len(l:buffer)-2 if l:buffer[l:i] =~ '^\s*$' && l:buffer[l:i+1] =~ '^\s*$' call remove(l:buffer,l:i) let l:rem=1 endif endif if l:rem == 0 let l:i+=1 endif endwhile endif " do the same with a:file let l:file=filter(a:file, 'v:val !~ "^\s*%"') let l:i = 0 if g:atp_compare_double_empty_lines == 0 || g:atp_compare_embedded_comments == 0 while l:i < len(l:file)-1 let l:rem=0 " remove comment lines at the end of a line if g:atp_compare_embedded_comments == 0 let l:file[l:i] = substitute(a:file[l:i],'%.*$','','') endif " remove double empty lines (i.e. from two conecutive empty lines " the first one is deleted, the second remains), if the line was " removed we do not need to add 1 to l:i (this is the role of " l:rem). if g:atp_compare_double_empty_lines == 0 && l:i < len(l:file)-2 if l:file[l:i] =~ '^\s*$' && l:file[l:i+1] =~ '^\s*$' call remove(l:file,l:i) let l:rem=1 endif endif if l:rem == 0 let l:i+=1 endif endwhile endif " This is the way to make it not sensitive on new line signs. " let file_j = join(l:file) " let buffer_j = join(l:buffer) " return file_j !=# buffer_j return l:file !=# l:buffer endfunction " function! s:sompare(file) " return Compare(a:file) " endfunction " This is very fast (0.002 sec on file with 2500 lines) " but the proble is that vimgrep greps the buffer rather than the file! " so it will not indicate any differences. function! NewCompare() let line = getline(".") let lineNr = line(".") let saved_loclist = getloclist(0) try exe "lvimgrep /^". escape(line, '\^$') . "$/j " . fnameescape(expand("%:p")) catch /E480:/ endtry " call setloclist(0, saved_loclist) let loclist = getloclist(0) call map(loclist, "v:val['lnum']") return !(index(loclist, lineNr)+1) endfunction "}}} " This function copies the file a:input to a:output "{{{ s:copy function! copy(input,output) call writefile(readfile(a:input),a:output) endfunction "}}} " CALL BACK: " (with the help of David Munger - LatexBox) "{{{ call back function! GetSid() "{{{ return matchstr(expand(''), '\zs\d\+_\ze.*$') endfunction let s:compiler_SID = s:GetSid() "}}} " Make the SID visible outside the script: " /used in LatexBox_complete.vim file/ let g:atp_compiler_SID = { fnamemodify(expand(''),':t') : s:compiler_SID } function! SidWrap(func) "{{{ return s:compiler_SID . a:func endfunction "}}} " CatchStatus {{{ function! CatchStatus(status) let b:atp_TexStatus=a:status endfunction " }}} " Callback {{{ " a:mode = a:verbose of s:compiler ( one of 'default', 'silent', " 'debug', 'verbose') " a:commnad = a:commmand of s:compiler " ( a:commnad = 'AU' if run from background) " " Uses b:atp_TexStatus which is equal to the value returned by tex " compiler. function! CallBack(mode) if g:atp_debugCallBack let b:mode = a:mode endif for cmd in keys(g:CompilerMsg_Dict) if b:atp_TexCompiler =~ '^\s*' . cmd . '\s*$' let Compiler = g:CompilerMsg_Dict[cmd] break else let Compiler = b:atp_TexCompiler endif endfor let b:atp_running = b:atp_running - 1 " Read the log file cg " If the log file is open re read it / it has 'autoread' opion set / checktime " redraw the status line /for the notification to appear as fast as " possible/ if a:mode != 'verbose' redrawstatus endif if b:atp_TexStatus && t:atp_DebugMode != "silent" if b:atp_ReloadOnError echomsg Compiler." exited with status " . b:atp_TexStatus else echomsg Compiler." exited with status " . b:atp_TexStatus . " output file not reloaded" endif elseif !g:atp_status_notification || !g:atp_statusline echomsg Compiler." finished" endif " End the debug mode if there are no errors if b:atp_TexStatus == 0 && t:atp_DebugMode == "debug" cclose echomsg b :atp_TexCompiler." finished with status " . b:atp_TexStatus . " going out of debuging mode." let t:atp_DebugMode == g:atp_DefaultDebugMode endif if t:atp_DebugMode == "debug" || a:mode == "debug" if !t:atp_QuickFixOpen ShowErrors endif " In debug mode, go to first error. if t:atp_DebugMode == "debug" cc endif endif endfunction "}}} "}}} " This function is called to run TeX compiler and friends as many times as necessary. " Makes references and bibliographies (supports bibtex), indexes. "{{{ MakeLatex " a:texfile full path to the tex file " a:index 0/1 " 0 - do not check for making index in this run " 1 - the opposite " a:0 == 0 || a:1 == 0 (i.e. the default) not run latex before /this might change in " the future/ " a:1 != 0 run latex first, regardless of the state of log/aux files. " " " The arguments are path to logfile and auxfile. " To Do: add support for TOC ! " To Do: when I will add proper check if bibtex should be done (by checking bbl file " or changes in bibliographies in input files), the bang will be used to update/or " not the aux|log|... files. " Function Arguments: " a:texfile = main tex file to use " a:did_bibtex = the number of times bibtex was already done MINUS 1 (should be 0 on start up) " a:did_index = 0/1 1 - did index " / to make an index it is enough to call: " latex ; makeindex ; latex / " a:time = [] - it will give time message (only if has("reltime")) " [0] - no time message. " a:did_firstrun = did the first run? (see a:1 below) " a:run = should be 1 on invocation: the number of the run " force = '!'/'' (see :h bang) " This only makes a difference with bibtex: " if removed citation to get the right Bibliography you need to use " 'Force' option in all other cases 'NoForce' is enough (and faster). " " a:1 = do the first run (by default: NO) - to obtain/update log|aux|idx|toc|... files. " /this is a weak NO: if one of the needed files not " readable it is used/ " " Some explanation notes: " references = referes to the bibliography " the pattern to match in log is based on the " phrase: 'Citation .* undefined' " cross_references = referes to the internal labels " phrase to check in the log file: " 'Label(s) may have changed. Rerun to get cross references right.' " table of contents = 'No file \f*\.toc' " needs reltime feature (used already in the command) " DEBUG: " errorfile /tmp/mk_log function! MakeLatex(texfile, did_bibtex, did_index, time, did_firstrun, run, force, ...) if a:time == [] && has("reltime") && len(a:time) != 1 let time = reltime() else let time = a:time endif if &filetype == "plaintex" echohl WarningMsg echo "plaintex is not supported" echohl None return "plaintex is not supported." endif " Prevent from infinite loops if a:run >= s:runlimit echoerr "ATP Error: MakeLatex in infinite loop." return "infinte loop." endif let b:atp_running= a:run == 1 ? b:atp_running+1 : 0 let runtex_before = a:0 == 0 || a:1 == 0 ? 0 : 1 let runtex_before = runtex_before if g:atp_debugML if a:run == 1 redir! > /tmp/mk_log else redir! >> /tmp/mk_log endif endif for cmd in keys(g:CompilerMsg_Dict) if b:atp_TexCompiler =~ '^\s*' . cmd . '\s*$' let Compiler = g:CompilerMsg_Dict[cmd] break else let Compiler = b:atp_TexCompiler endif endfor let compiler_SID = s:compiler_SID let g:ml_debug = "" let mode = ( g:atp_DefaultDebugMode == 'verbose' ? 'debug' : g:atp_DefaultDebugMode ) let tex_options = " -interaction nonstopmode -output-directory=" . fnameescape(b:atp_OutDir) . " " . b:atp_TexOptions . " " " This supports b:atp_OutDir let saved_cwd = getcwd() exe "lcd " . fnameescape(b:atp_OutDir) let texfile = fnamemodify(a:texfile, ":t") let logfile = fnamemodify(texfile, ":r") . ".log" let auxfile = fnamemodify(texfile, ":r") . ".aux" let bibfile = fnamemodify(texfile, ":r") . ".bbl" let idxfile = fnamemodify(texfile, ":r") . ".idx" let indfile = fnamemodify(texfile, ":r") . ".ind" let tocfile = fnamemodify(texfile, ":r") . ".toc" let loffile = fnamemodify(texfile, ":r") . ".lof" let lotfile = fnamemodify(texfile, ":r") . ".lot" let thmfile = fnamemodify(texfile, ":r") . ".thm" if b:atp_TexCompiler =~ '^\%(pdflatex\|pdftex\|xetex\|context\|luatex\)$' let ext = ".pdf" else let ext = ".dvi" endif let outfile = fnamemodify(texfile, ":r") . ext if g:atp_debugML silent echo a:run . " BEGIN " . strftime("%c") silent echo "TEXFILE: ".texfile silent echo a:run . " logfile=" . logfile . " " . filereadable(logfile) . " auxfile=" . auxfile . " " . filereadable(auxfile). " runtex_before=" . runtex_before . " a:force=" . a:force endif let saved_pos = getpos(".") keepjumps call setpos(".", [0,1,1,0]) keepjumps let stop_line=search('\m\\begin\s*{document}','nW') let makeidx = search('\m^[^%]*\\makeindex', 'n', stop_line) keepjumps call setpos(".", saved_pos) " We use location list which should be restored. let saved_loclist = copy(getloclist(0)) " grep in aux file for " 'Citation .* undefined\|Rerun to get cross-references right\|Writing index file' let saved_llist = getloclist(0) " execute "silent! lvimgrep /Citation\\_s\\_.*\\_sundefined\\|Label(s)\\_smay\\_shave\\_schanged.\\|Writing\\_sindex\\_sfile/j " . fnameescape(logfile) execute "silent! lvimgrep /C\\n\\=i\\n\\=t\\n\\=a\\n\\=t\\n\\=i\\n\\=o\\n\\=n\\_s\\_.*\\_su\\n\\=n\\n\\=d\\n\\=e\\n\\=f\\n\\=i\\n\\=n\\n\\=e\\n\\=d\\|L\\n\\=a\\n\\=b\\n\\=e\\n\\=l\\n\\=(\\n\\=s\\n\\=)\\_sm\\n\\=a\\n\\=y\\_sh\\n\\=a\\n\\=v\\n\\=e\\_sc\\n\\=h\\n\\=a\\n\\=n\\n\\=g\\n\\=e\\n\\=d\\n\\=.\\|W\\n\\=r\\n\\=i\\n\\=t\\n\\=i\\n\\=n\\n\\=g\\_si\\n\\=n\\n\\=d\\n\\=e\\n\\=x\\_sf\\n\\=i\\n\\=l\\n\\=e/j " . fnameescape(logfile) let location_list = copy(getloclist(0)) call setloclist(0, saved_llist) " Check references: if g:atp_debugML silent echo a:run . " location_list=" . string(len(location_list)) silent echo a:run . " references_list=" . string(len(filter(copy(location_list), 'v:val["text"] =~ "Citation"'))) endif let references = len(filter(copy(location_list), 'v:val["text"] =~ "Citation"')) == 0 ? 0 : 1 " Check what to use to make the 'Bibliography': let saved_llist = getloclist(0) execute 'silent! lvimgrep /\\bibdata\s*{/j ' . fnameescape(auxfile) " Note: if the auxfile is not there it returns 0 but this is the best method for " looking if we have to use 'bibtex' as the bibliography might be not written in " the main file. let bibtex = len(getloclist(0)) == 0 ? 0 : 1 call setloclist(0, saved_llist) if g:atp_debugML silent echo a:run . " references=" . references . " bibtex=" . bibtex . " a:did_bibtex=" . a:did_bibtex endif " Check cross-references: let cross_references = len(filter(copy(location_list), 'v:val["text"]=~"Rerun"'))==0?0:1 if g:atp_debugML silent echo a:run . " cross_references=" . cross_references endif " Check index: let idx_cmd = "" if makeidx " The index file is written iff " 1) package makeidx is declared " 2) the preambule contains \makeindex command, then log has a line: "Writing index file" " the 'index' variable is equal 1 iff the two conditions are met. let index = len(filter(copy(location_list), 'v:val["text"] =~ "Writing index file"')) == 0 ? 0 : 1 if index let idx_cmd = " makeindex " . idxfile . " ; " endif else let index = 0 endif if g:atp_debugML silent echo a:run . " index=" . index . " makeidx=" . makeidx . " idx_cdm=" . idx_cmd . " a:did_index=" . a:did_index endif " Check table of contents: let saved_llist = getloclist(0) execute "silent! lvimgrep /\\\\openout\\d\\+/j " . fnameescape(logfile) let open_out = map(getloclist(0), "v:val['text']") call setloclist(0, saved_llist) if filereadable(logfile) && a:force == "" let toc = ( len(filter(deepcopy(open_out), "v:val =~ \"toc\'\"")) ? 1 : 0 ) let lof = ( len(filter(deepcopy(open_out), "v:val =~ \"lof\'\"")) ? 1 : 0 ) let lot = ( len(filter(deepcopy(open_out), "v:val =~ \"lot\'\"")) ? 1 : 0 ) let thm = ( len(filter(deepcopy(open_out), "v:val =~ \"thm\'\"")) ? 1 : 0 ) else " This is not an efficient way and it is not good for long files with input " lines and lists in not common position. let save_pos = getpos(".") call cursor(1,1) let toc = search('\\tableofcontents', 'nw') call cursor(line('$'), 1) call cursor(line('.'), col('$')) let lof = search('\\listoffigures', 'nbw') let lot = search('\\listoffigures', 'nbw') if atplib#SearchPackage('ntheorem') let thm = search('\\listheorems', 'nbw') else let thm = 0 endif keepjumps call setpos(".", save_pos) endif if g:atp_debugML silent echo a:run." toc=".toc." lof=".lof." lot=".lot." open_out=".string(open_out) endif " Run tex compiler for the first time: let logfile_readable = filereadable(logfile) let auxfile_readable = filereadable(auxfile) let idxfile_readable = filereadable(idxfile) let tocfile_readable = filereadable(tocfile) let loffile_readable = filereadable(loffile) let lotfile_readable = filereadable(lotfile) let thmfile_readable = filereadable(thmfile) let condition = !logfile_readable || !auxfile_readable || !thmfile_readable && thm || \ ( makeidx && !idxfile_readable ) || \ !tocfile_readable && toc || !loffile_readable && lof || !lotfile_readable && lot || \ runtex_before if g:atp_debugML silent echo a:run . " log_rea=" . logfile_readable . " aux_rea=" . auxfile_readable . " idx_rea&&mke=" . ( makeidx && idxfile_readable ) . " runtex_before=" . runtex_before silent echo a:run . " Run First " . condition endif if condition if runtex_before " Do not write project script file while saving the file. let atp_ProjectScript = ( exists("g:atp_ProjectScript") ? g:atp_ProjectScript : -1 ) let g:atp_ProjectScript = 0 " disable WriteProjectScript let eventignore = &l:eventignore setl eventignore+=BufWrite w let &l:eventignore = eventignore if atp_ProjectScript == -1 unlet g:atp_ProjectScript else let g:atp_ProjectScript = atp_ProjectScript endif endif let did_bibtex = 0 let callback_cmd = v:progname . " --servername " . v:servername . " --remote-expr \"" . compiler_SID . \ "MakeLatex\(\'".fnameescape(texfile)."\', ".did_bibtex.", 0, [".time[0].",".time[1]."], ". \ a:did_firstrun.", ".(a:run+1).", \'".a:force."\'\)\"" let cmd = b:atp_TexCompilerVariable . " " . b:atp_TexCompiler . tex_options . fnameescape(atplib#FullPath(texfile)) . " ; " . callback_cmd if g:atp_debugML let g:ml_debug .= "First run. (make log|aux|idx file)" . " [" . cmd . "]#" silent echo a:run . " Run First CMD=" . cmd let g:debug_cmd=cmd redir END endif redraw echomsg "[MakeLatex] Updating files [".Compiler."]." call system("(" . cmd . " )&") exe "lcd " . fnameescape(saved_cwd) return "Making log file or aux file" endif " Run tex compiler: if a:did_firstrun && !bibtex && a:run == 2 "Note: in this place we should now correctly if bibtex is in use or not, "if not and we did first run we can count it. /the a:did_bibtex variable will "not be updated/ let did_bibtex = a:did_bibtex + 1 else let did_bibtex = a:did_bibtex endif let bib_condition_force = ( (references && !bibtex) || bibtex ) && did_bibtex <= 1 let bib_condition_noforce = ( references && did_bibtex <= 1 ) let condition_force = bib_condition_force || cross_references || index && !a:did_index || \ ( ( toc || lof || lot || thm ) && a:run < 2 ) let condition_noforce = bib_condition_noforce || cross_references || index && !a:did_index || \ ( ( toc || lof || lot || thm ) && a:run < 2 ) if g:atp_debugML silent echo a:run . " Run Second NoForce:" . ( condition_noforce && a:force == "" ) . " Force:" . ( condition_force && a:force == "!" ) silent echo a:run . " BIBTEX: did_bibtex[updated]=" . did_bibtex . " references=" . references . " CROSSREF:" . cross_references . " INDEX:" . (index && !a:did_index) endif if ( condition_force && a:force == "!" ) || ( condition_noforce && a:force == "" ) let cmd = '' let bib_cmd = 'bibtex ' . fnameescape(auxfile) . ' ; ' let idx_cmd = 'makeindex ' . fnameescape(idxfile) . ' ; ' let message = "Making:" if ( bib_condition_force && a:force == "!" ) || ( bib_condition_noforce && a:force == "" ) let bib_msg = ( bibtex ? ( did_bibtex == 0 ? " [bibtex,".Compiler."]" : " [".Compiler."]" ) : " [".Compiler."]" ) let message .= " references".bib_msg."," endif if toc && a:run <= 2 let message .= " toc," endif if lof && a:run <= 2 let message .= " lof," endif if lot && a:run <= 2 let message .= " lot," endif if thm && a:run <= 2 let message .= " theorem list," endif if cross_references let message .= " cross-references," endif if !a:did_index && index && idxfile_readable let message .= " index [makeindex]." endif let message = substitute(message, ',\s*$', '.', '') if !did_bibtex && auxfile_readable && bibtex let cmd .= bib_cmd . " " let did_bibtex += 1 else let did_bibtex += 1 endif " If index was done: if a:did_index let did_index = 1 " If not and should be and the idx_file is readable elseif index && idxfile_readable let cmd .= idx_cmd . " " let did_index = 1 " If index should be done, wasn't but the idx_file is not readable (we need " to make it first) elseif index let did_index = 0 " If the index should not be done: else let did_index = 1 endif let callback_cmd = v:progname . " --servername " . v:servername . " --remote-expr \"" . compiler_SID . \ "MakeLatex\(\'".fnameescape(texfile)."\', ".did_bibtex." , ".did_index.", [".time[0].",".time[1]."], ". \ a:did_firstrun.", ".(a:run+1).", \'".a:force."\'\)\"" let cmd .= b:atp_TexCompilerVariable . " " . b:atp_TexCompiler . tex_options . fnameescape(atplib#FullPath(texfile)) . " ; " . callback_cmd if g:atp_debugML silent echo a:run . " a:did_bibtex="a:did_bibtex . " did_bibtex=" . did_bibtex silent echo a:run . " Run Second CMD=" . cmd redir END endif echomsg "[MakeLatex] " . message call system("(" . cmd . ")&") exe "lcd " . fnameescape(saved_cwd) return "Making references|cross-references|index." endif " Post compeltion works: if g:atp_debugML silent echo a:run . " END" redir END endif redraw if time != [] && len(time) == 2 let show_time = matchstr(reltimestr(reltime(time)), '\d\+\.\d\d') endif if max([(a:run-1), 0]) == 1 echomsg "[MakeLatex] " . max([(a:run-1), 0]) . " time in " . show_time . "sec." else echomsg "[MakeLatex] " . max([(a:run-1), 0]) . " times in " . show_time . "sec." endif if b:atp_running >= 1 let b:atp_running = b:atp_running - 1 endif " THIS is a right place to call the viewer to reload the file " and the callback mechanism /debugging stuff/. if b:atp_Viewer == 'xpdf' && s:xpdfpid() != "" let pdffile = fnamemodify(a:texfile, ":r") . ".pdf" let Reload_Viewer = b:atp_Viewer." -remote ".shellescape(b:atp_XpdfServer)." -reload &" call system(Reload_Viewer) endif exe "lcd " . fnameescape(saved_cwd) return "Proper end" endfunction "}}} " THE MAIN COMPILER FUNCTION: " {{{ s:Compiler " This is the MAIN FUNCTION which sets the command and calls it. " NOTE: the argument is not escaped! " a:verbose = silent/verbose/debug " debug -- switch to show errors after compilation. " verbose -- show compiling procedure. " silent -- compile silently (gives status information if fails) " a:start = 0/1/2 " 1 start viewer " 2 start viewer and make reverse search " function! Compiler(bibtex, start, runs, verbose, command, filename, bang) if !has('gui') && a:verbose == 'verbose' && b:atp_running > 0 redraw! echomsg "Please wait until compilation stops." return endif if g:atp_debugCompiler redir! >> /tmp/ATP_CompilerLog silent echomsg "________ATP_COMPILER_LOG_________" silent echomsg "changedtick=" . b:changedtick . " atp_changedtick=" . b:atp_changedtick silent echomsg "a:bibtex=" . a:bibtex . " a:start=" . a:start . " a:runs=" . a:runs . " a:verbose=" . a:verbose . " a:command=" . a:command . " a:filename=" . a:filename . " a:bang=" . a:bang silent echomsg "1 b:changedtick=" . b:changedtick . " b:atp_changedtick" . b:atp_changedtick . " b:atp_running=" . b:atp_running endif if has('clientserver') && !empty(v:servername) && g:atp_callback && a:verbose != 'verbose' let b:atp_running+=1 endif call atplib#outdir() " IF b:atp_TexCompiler is not compatible with the viewer " ToDo: (move this in a better place). (luatex can produce both pdf and dvi " files according to options so this is not the right approach.) if t:atp_DebugMode != "silent" && b:atp_TexCompiler !~ "luatex" && \ (b:atp_TexCompiler =~ "^\s*\%(pdf\|xetex\)" && b:atp_Viewer == "xdvi" ? 1 : \ b:atp_TexCompiler !~ "^\s*pdf" && b:atp_TexCompiler !~ "xetex" && (b:atp_Viewer == "xpdf" || b:atp_Viewer == "epdfview" || b:atp_Viewer == "acroread" || b:atp_Viewer == "kpdf")) echohl WaningMsg | echomsg "Your ".b:atp_TexCompiler." and ".b:atp_Viewer." are not compatible:" echomsg "b:atp_TexCompiler=" . b:atp_TexCompiler echomsg "b:atp_Viewer=" . b:atp_Viewer endif " there is no need to run more than s:runlimit (=5) consecutive runs " this prevents from running tex as many times as the current line " what can be done by a mistake using the range for the command. if a:runs > s:runlimit let runs = s:runlimit else let runs = a:runs endif let tmpdir=b:atp_TmpDir . matchstr(tempname(), '\/\w\+\/\d\+') let tmpfile=atplib#append(tmpdir, "/") . fnamemodify(a:filename,":t:r") if exists("*mkdir") call mkdir(tmpdir, "p", 0700) else echoerr 'Your vim doesn't have mkdir function' endif " SET THE NAME OF OUTPUT FILES " first set the extension pdf/dvi let ext = get(g:atp_CompilersDict, matchstr(b:atp_TexCompiler, '^\s*\zs\S\+\ze'), ".pdf") " check if the file is a symbolic link, if it is then use the target " name. let link=system("readlink " . a:filename) if link != "" let basename=fnamemodify(link,":r") else let basename=a:filename endif " finally, set the output file names. let outfile = b:atp_OutDir . fnamemodify(basename,":t:r") . ext let outaux = b:atp_OutDir . fnamemodify(basename,":t:r") . ".aux" let tmpaux = fnamemodify(tmpfile, ":r") . ".aux" let tmptex = fnamemodify(tmpfile, ":r") . ".tex" let outlog = b:atp_OutDir . fnamemodify(basename,":t:r") . ".log" let syncgzfile = b:atp_OutDir . fnamemodify(basename,":t:r") . ".synctex.gz" let syncfile = b:atp_OutDir . fnamemodify(basename,":t:r") . ".synctex" " COPY IMPORTANT FILES TO TEMP DIRECTORY WITH CORRECT NAME " except log and aux files. let list = copy(g:keep) call filter(list, 'v:val != "log" && v:val != "aux"') for i in list let ftc = b:atp_OutDir . fnamemodify(basename,":t:r") . "." . i if filereadable(ftc) call s:copy(ftc,tmpfile . "." . i) endif endfor " HANDLE XPDF RELOAD if b:atp_Viewer =~ '^\s*xpdf\>' if a:start "if xpdf is not running and we want to run it. let Reload_Viewer = b:atp_Viewer . " -remote " . shellescape(b:atp_XpdfServer) . " " . shellescape(outfile) . " ; " else " TIME: this take 1/3 of time! 0.039 if xpdfpid() != "" "if xpdf is running (then we want to reload it). "This is where I use 'ps' command to check if xpdf is "running. let Reload_Viewer = b:atp_Viewer . " -remote " . shellescape(b:atp_XpdfServer) . " -reload ; " else "if xpdf is not running (but we do not want "to run it). let Reload_Viewer = " " endif endif else if a:start " if b:atp_Viewer is not running and we want to open it. let Reload_Viewer = b:atp_Viewer . " " . shellescape(outfile) . " ; " " If run through RevSearch command use source specials rather than " just reload: if str2nr(a:start) == 2 let synctex = s:SidWrap('SyncTex') let callback_rs_cmd = " vim " . " --servername " . v:servername . " --remote-expr " . "'".synctex."()' ; " let Reload_Viewer = callback_rs_cmd endif else " if b:atp_Viewer is not running then we do not want to " open it. let Reload_Viewer = " " endif endif if g:atp_debugCompiler let g:Reload_Viewer = Reload_Viewer endif " IF OPENING NON EXISTING OUTPUT FILE " only xpdf needs to be run before (we are going to reload it) if a:start && b:atp_Viewer == "xpdf" let xpdf_options = ( exists("g:atp_xpdfOptions") ? g:atp_xpdfOptions : "" )." ".getbufvar(0, "atp_xpdfOptions") let start = b:atp_Viewer . " -remote " . shellescape(b:atp_XpdfServer) . " " . xpdf_options . " & " else let start = "" endif " SET THE COMMAND let comp = b:atp_TexCompilerVariable . " " . b:atp_TexCompiler . " " . b:atp_TexOptions . " -interaction=" . s:texinteraction . " -output-directory=" . shellescape(tmpdir) . " " . shellescape(a:filename) let vcomp = b:atp_TexCompilerVariable . " " . b:atp_TexCompiler . " " . b:atp_TexOptions . " -interaction=errorstopmode -output-directory=" . shellescape(tmpdir) . " " . shellescape(a:filename) " make function: " let make = "vim --servername " . v:servername . " --remote-expr 'MakeLatex\(\"".tmptex."\",1,0\)'" if a:verbose == 'verbose' let texcomp=vcomp else let texcomp=comp endif if runs >= 2 && a:bibtex != 1 " how many times we want to call b:atp_TexCompiler let i=1 while i < runs - 1 let i+=1 let texcomp=texcomp . " ; " . comp endwhile if a:verbose != 'verbose' let texcomp=texcomp . " ; " . comp else let texcomp=texcomp . " ; " . vcomp endif endif if a:bibtex == 1 " this should be decided using the log file as well. if filereadable(outaux) call s:copy(outaux,tmpfile . ".aux") let texcomp="bibtex " . shellescape(tmpfile) . ".aux ; " . comp . " 1>/dev/null 2>&1 " else let texcomp=comp . " ; clear ; bibtex " . shellescape(tmpfile) . ".aux ; " . comp . " 1>/dev/null 2>&1 " endif if a:verbose != 'verbose' let texcomp=texcomp . " ; " . comp else let texcomp=texcomp . " ; " . vcomp endif endif " catch the status if has('clientserver') && v:servername != "" && g:atp_callback == 1 let catchstatus = s:SidWrap('CatchStatus') let catchstatus_cmd = 'vim ' . ' --servername ' . v:servername . ' --remote-expr ' . \ shellescape(catchstatus) . '\($?\) ; ' else let catchstatus_cmd = '' endif " copy output file (.pdf\|.ps\|.dvi) let cpoptions = "--remove-destination" let cpoutfile = g:atp_cpcmd." ".cpoptions." ".shellescape(atplib#append(tmpdir,"/"))."*".ext." ".shellescape(atplib#append(b:atp_OutDir,"/"))." ; " if a:start let command = "(" . texcomp . " ; (" . catchstatus_cmd . " " . cpoutfile . " " . Reload_Viewer . " ) || ( ". catchstatus_cmd . " " . cpoutfile . ") ; " else " Reload on Error: " for xpdf it copies the out file but does not reload the xpdf " server for other viewers it simply doesn't copy the out file. if b:atp_ReloadOnError || a:bang == "!" if a:bang == "!" let command="( ".texcomp." ; ".catchstatus_cmd." ".g:atp_cpcmd." ".cpoptions." ".shellescape(tmpaux)." ".shellescape(b:atp_OutDir)." ; ".cpoutfile." ".Reload_Viewer else let command="( (".texcomp." && ".g:atp_cpcmd." ".cpoptions." ".shellescape(tmpaux)." ".shellescape(b:atp_OutDir)." ) ; ".catchstatus_cmd." ".cpoutfile." ".Reload_Viewer endif else if b:atp_Viewer =~ '\' let command="( ".texcomp." && (".catchstatus_cmd.cpoutfile." ".Reload_Viewer." ".g:atp_cpcmd." ".cpoptions." ".shellescape(tmpaux)." ".shellescape(b:atp_OutDir)." ) || (".catchstatus_cmd." ".cpoutfile.") ; " else let command="(".texcomp." && (".catchstatus_cmd.cpoutfile." ".Reload_Viewer." ".g:atp_cpcmd." ".cpoptions." ".shellescape(tmpaux)." ".shellescape(b:atp_OutDir)." ) || (".catchstatus_cmd.") ; " endif endif endif if g:atp_debugCompiler silent echomsg "Reload_Viewer=" . Reload_Viewer let g:Reload_Viewer = Reload_Viewer let g:command = command elseif g:atp_debugCompiler >= 2 silent echomsg "command=" . command endif " Preserve files with extension belonging to the g:keep list variable. let copy_cmd="" let j=1 for i in filter(copy(g:keep), 'v:val != "aux"') " ToDo: this can be done using internal vim functions. let copycmd=g:atp_cpcmd." ".cpoptions." ".shellescape(atplib#append(tmpdir,"/")). \ "*.".i." ".shellescape(atplib#append(b:atp_OutDir,"/")) if j == 1 let copy_cmd=copycmd else let copy_cmd=copy_cmd . " ; " . copycmd endif let j+=1 endfor if g:atp_debugCompiler let g:copy_cmd = copy_cmd endif let command=command . " " . copy_cmd . " ; " " Callback: if has('clientserver') && v:servername != "" && g:atp_callback == 1 let callback = s:SidWrap('CallBack') let callback_cmd = ' vim ' . ' --servername ' . v:servername . ' --remote-expr ' . \ shellescape(callback).'\(\"'.a:verbose.'\"\)'. " ; " let command = command . " " . callback_cmd endif if g:atp_debugCompiler silent echomsg "callback_cmd=" . callback_cmd endif let rmtmp="rm -rf " . shellescape(tmpdir) . "; " let command=command . " " . rmtmp . ") &" if str2nr(a:start) != 0 let command=start . command endif " Take care about backup and writebackup options. let backup=&backup let writebackup=&writebackup if a:command == "AU" if &backup || &writebackup | setlocal nobackup | setlocal nowritebackup | endif endif " This takes lots of time! 0.049s (more than 1/3) if g:atp_debugCompiler silent echomsg "BEFORE WRITING: b:changedtick=" . b:changedtick . " b:atp_changedtick=" . b:atp_changedtick . " b:atp_running=" . b:atp_running endif " disable WriteProjectScript let eventignore = &l:eventignore setl eventignore+=BufWrite w let &l:eventignore = eventignore " let b:atp_changedtick += 1 if g:atp_debugCompiler silent echomsg "AFTER WRITING: b:changedtick=" . b:changedtick . " b:atp_changedtick=" . b:atp_changedtick . " b:atp_running=" . b:atp_running endif if a:command == "AU" let &l:backup=backup let &l:writebackup=writebackup endif if a:verbose != 'verbose' let g:atp_TexOutput=system(command) else let command="!clear;" . texcomp . " " . cpoutfile . " " . copy_cmd exe command endif unlockvar g:atp_TexCommand let g:atp_TexCommand=command lockvar g:atp_TexCommand if g:atp_debugCompiler silent echomsg "command=" . command redir END endif endfunction "}}} " AUTOMATIC TEX PROCESSING: " {{{ s:auTeX " This function calls the compilers in the background. It Needs to be a global " function (it is used in options.vim, there is a trick to put function into " a dictionary ... ) augroup ATP_changedtick au! au BufEnter *.tex :let b:atp_changedtick = b:changedtick au BufWritePost *.tex :let b:atp_changedtick = b:changedtick augroup END function! auTeX() " Using vcscommand plugin the diff window ends with .tex thus the autocommand " applies but the filetype is 'diff' thus we can switch tex processing by: if &l:filetype !~ "tex$" return "wrong file type" endif let atp_MainFile = atplib#FullPath(b:atp_MainFile) let mode = ( g:atp_DefaultDebugMode == 'verbose' ? 'debug' : g:atp_DefaultDebugMode ) if !b:atp_autex return "autex is off" endif " if the file (or input file is modified) compile the document if filereadable(expand("%")) if g:atp_Compare == "changedtick" let cond = ( b:changedtick != b:atp_changedtick ) else let cond = ( s:compare(readfile(expand("%"))) ) endif if cond " This is for changedtick only let b:atp_changedtick = b:changedtick + 1 " +1 because s:Compiler saves the file what increases b:changedtick by 1. " this is still needed as I use not nesting BufWritePost autocommand to set " b:atp_changedtick (by default autocommands do not nest). Alternate solution is to " run s:AuTeX() with nested autocommand (|autocmd-nested|). But this seems " to be less user friendly, nested autocommands allows only 10 levels of " nesting (which seems to be high enough). " " if NewCompare() call s:Compiler(0, 0, b:atp_auruns, mode, "AU", atp_MainFile, "") redraw return "compile" endif " if compiling for the first time else try " Do not write project script file while saving the file. let atp_ProjectScript = ( exists("g:atp_ProjectScript") ? g:atp_ProjectScript : -1 ) let g:atp_ProjectScript = 0 w if atp_ProjectScript == -1 unlet g:atp_ProjectScript else let g:atp_ProjectScript = atp_ProjectScript endif catch /E212:/ echohl ErrorMsg echomsg expand("%") . "E212: Cannon open file for writing" echohl Normal return " E212" catch /E382:/ " This option can be set by VCSCommand plugin using VCSVimDiff command return " E382" endtry call s:Compiler(0, 0, b:atp_auruns, mode, "AU", atp_MainFile, "") redraw return "compile for the first time" endif return "files does not differ" endfunction " This is set by SetProjectName (options.vim) where it should not! augroup ATP_auTeX au! au CursorHold *.tex call s:auTeX() if g:atp_insert_updatetime au CursorHoldI *.tex call s:auTeX() endif augroup END "}}} " Related Functions " {{{ TeX " a:runs = how many consecutive runs " a:1 = one of 'default','silent', 'debug', 'verbose' " if not specified uses 'default' mode " (g:atp_DefaultDebugMode). function! TeX(runs, bang, ...) let atp_MainFile = atplib#FullPath(b:atp_MainFile) " echomsg "TEX_1 CHANGEDTICK=" . b:changedtick . " " . b:atp_running if a:0 >= 1 let mode = ( a:1 != 'default' ? a:1 : g:atp_DefaultDebugMode ) else let mode = g:atp_DefaultDebugMode endif for cmd in keys(g:CompilerMsg_Dict) if b:atp_TexCompiler =~ '^\s*' . cmd . '\s*$' let Compiler = g:CompilerMsg_Dict[cmd] break else let Compiler = b:atp_TexCompiler endif endfor " echomsg "TEX_2 CHANGEDTICK=" . b:changedtick . " " . b:atp_running if l:mode != 'silent' if a:runs > 2 && a:runs <= 5 echomsg Compiler . " will run " . a:1 . " times." elseif a:runs == 2 echomsg Compiler . " will run twice." elseif a:runs == 1 echomsg Compiler . " will run once." elseif a:runs > 5 echomsg Compiler . " will run " . s:runlimit . " times." endif endif " echomsg "TEX_3 CHANGEDTICK=" . b:changedtick . " " . b:atp_running call s:Compiler(0,0, a:runs, mode, "COM", atp_MainFile, a:bang) " echomsg "TEX_4 CHANGEDTICK=" . b:changedtick . " " . b:atp_running endfunction function! TEX_Comp(ArgLead, CmdLine, CursorPos) return filter(['silent', 'debug', 'verbose'], "v:val =~ '^' . a:ArgLead") endfunction " command! -buffer -count=1 VTEX :call TeX(, 'verbose') noremap ATP_TeXCurrent :call TeX(v:count1, "", t:atp_DebugMode) noremap ATP_TeXDefault :call TeX(v:count1, "", 'default') noremap ATP_TeXSilent :call TeX(v:count1, "", 'silent') noremap ATP_TeXDebug :call TeX(v:count1, "", 'debug') noremap ATP_TeXVerbose :call TeX(v:count1, "", 'verbose') inoremap iATP_TeXVerbose :call TeX(v:count1, "", 'verbose') "}}} "{{{ Bibtex function! SimpleBibtex() let bibcommand = "bibtex " let atp_MainFile = atplib#FullPath(b:atp_MainFile) let auxfile = fnamemodify(resolve(atp_MainFile),":t:r") . ".aux" " When oupen_out = p (in texmf.cnf) bibtex can only open files in the working " directory and they should no be given with full path: " p (paranoid) : as `r' and disallow going to parent directories, and " restrict absolute paths to be under $TEXMFOUTPUT. let saved_cwd = getcwd() exe "lcd " . fnameescape(b:atp_OutDir) let g:cwd = getcwd() if filereadable(auxfile) let command = bibcommand . shellescape(l:auxfile) let g:command = command echo system(command) else echomsg "aux file " . auxfile . " not readable." endif exe "lcd " . fnameescape(saved_cwd) endfunction nnoremap SimpleBibtex :call SimpleBibtex() function! Bibtex(bang,...) if a:bang == "" call SimpleBibtex() return endif let atp_MainFile = atplib#FullPath(b:atp_MainFile) if a:0 >= 1 let mode = ( a:1 != 'default' ? a:1 : g:atp_DefaultDebugMode ) else let mode = g:atp_DefaultDebugMode endif call s:Compiler(1, 0, 0, mode, "COM", atp_MainFile, "") endfunction nnoremap BibtexDefault :call Bibtex("", "") nnoremap BibtexSilent :call Bibtex("", "silent") nnoremap BibtexDebug :call Bibtex("", "debug") nnoremap BibtexVerbose :call Bibtex("", "verbose") "}}} " Show Errors Function " (some error tools are in various.vim: ':ShowErrors o') " {{{ SHOW ERRORS " " this functions sets errorformat according to the flag given in the argument, " possible flags: " e - errors (or empty flag) " w - all warning messages " c - citation warning messages " r - reference warning messages " f - font warning messages " fi - font warning and info messages " F - files " p - package info messages " {{{ s:SetErrorFormat " first argument is a word in flags " the default is a:1=e /show only error messages/ function! SetErrorFormat(...) if a:0 > 0 let b:arg1=a:1 if a:0 > 1 let b:arg1.=" ".a:2 endif endif let &l:errorformat="" if a:0 == 0 || a:0 > 0 && a:1 =~ 'e' if &l:errorformat == "" let &l:errorformat= "%E!\ LaTeX\ %trror:\ %m,\%E!\ %m,%E!pdfTeX %trror:\ %m" else let &l:errorformat= &l:errorformat . ",%E!\ LaTeX\ %trror:\ %m,\%E!\ %m,%E!pdfTeX %trror:\ %m" endif endif if a:0>0 && a:1 =~ 'w' if &l:errorformat == "" let &l:errorformat='%WLaTeX\ %tarning:\ %m\ on\ input\ line\ %l%., \%WLaTeX\ %.%#Warning:\ %m, \%Z(Font) %m\ on\ input\ line\ %l%., \%+W%.%#\ at\ lines\ %l--%*\\d' else let &l:errorformat= &l:errorformat . ',%WLaTeX\ %tarning:\ %m\ on\ input\ line\ %l%., \%WLaTeX\ %.%#Warning:\ %m, \%Z(Font) %m\ on\ input\ line\ %l%., \%+W%.%#\ at\ lines\ %l--%*\\d' " let &l:errorformat= &l:errorformat . ',%+WLaTeX\ %.%#Warning:\ %.%#line\ %l%.%#, " \%WLaTeX\ %.%#Warning:\ %m, " \%+W%.%#\ at\ lines\ %l--%*\\d' endif endif if a:0>0 && a:1 =~ '\Cc' " NOTE: " I would like to include 'Reference/Citation' as an error message (into %m) " but not include the 'LaTeX Warning:'. I don't see how to do that actually. " The only solution, that I'm aware of, is to include the whole line using " '%+W' but then the error messages are long and thus not readable. if &l:errorformat == "" let &l:errorformat = "%WLaTeX\ Warning:\ Citation\ %m\ on\ input\ line\ %l%.%#" else let &l:errorformat = &l:errorformat . ",%WLaTeX\ Warning:\ Citation\ %m\ on\ input\ line\ %l%.%#" endif endif if a:0>0 && a:1 =~ '\Cr' if &l:errorformat == "" let &l:errorformat = "%WLaTeX\ Warning:\ Reference %m on\ input\ line\ %l%.%#,%WLaTeX\ %.%#Warning:\ Reference %m,%C %m on input line %l%.%#" else let &l:errorformat = &l:errorformat . ",%WLaTeX\ Warning:\ Reference %m on\ input\ line\ %l%.%#,%WLaTeX\ %.%#Warning:\ Reference %m,%C %m on input line %l%.%#" endif endif if a:0>0 && a:1 =~ '\Cf' if &l:errorformat == "" let &l:errorformat = "%WLaTeX\ Font\ Warning:\ %m,%Z(Font) %m on input line %l%.%#" else let &l:errorformat = &l:errorformat . ",%WLaTeX\ Font\ Warning:\ %m,%Z(Font) %m on input line %l%.%#" endif endif if a:0>0 && a:1 =~ '\Cfi' if &l:errorformat == "" let &l:errorformat = '%ILatex\ Font\ Info:\ %m on input line %l%.%#, \%ILatex\ Font\ Info:\ %m, \%Z(Font) %m\ on input line %l%.%#, \%C\ %m on input line %l%.%#' else let &l:errorformat = &l:errorformat . ',%ILatex\ Font\ Info:\ %m on input line %l%.%#, \%ILatex\ Font\ Info:\ %m, \%Z(Font) %m\ on input line %l%.%#, \%C\ %m on input line %l%.%#' endif endif if a:0>0 && a:1 =~ '\CF' if &l:errorformat == "" let &l:errorformat = 'File: %m' else let &l:errorformat = &l:errorformat . ',File: %m' endif endif if a:0>0 && a:1 =~ '\Cp' if &l:errorformat == "" let &l:errorformat = 'Package: %m' else let &l:errorformat = &l:errorformat . ',Package: %m' endif endif if &l:errorformat != "" let pm = ( g:atp_show_all_lines == 1 ? '+' : '-' ) let l:dont_ignore = 0 if a:0 >= 1 && a:1 =~ '\cALL' let l:dont_ignore = 1 let pm = '+' endif let b:dont_ignore=l:dont_ignore.a:0 let &l:errorformat = &l:errorformat.", \%Cl.%l\ %m, \%".pm."C\ \ %m%.%#, \%".pm."C%.%#-%.%#, \%".pm."C%.%#[]%.%#, \%".pm."C[]%.%#, \%".pm."C%.%#%[{}\\]%.%#, \%".pm."C<%.%#>%.%#, \%".pm."C%m, \%".pm."GSee\ the\ LaTeX%m, \%".pm."GType\ \ H\ %m, \%".pm."G%.%#\ (C)\ %.%#, \%".pm."G(see\ the\ transcript%.%#), \%-G\\s%#" if (g:atp_ignore_unmatched && !g:atp_show_all_lines) exec 'setlocal efm+=%-G%.%#' elseif l:dont_ignore exec 'setlocal efm+=%-G%.%#' endif let &l:errorformat = &l:errorformat.", \%".pm."O(%*[^()])%r, \%".pm."O%*[^()](%*[^()])%r, \%".pm."P(%f%r, \%".pm."P\ %\\=(%f%r, \%".pm."P%*[^()](%f%r, \%".pm."P[%\\d%[^()]%#(%f%r" if g:atp_ignore_unmatched && !g:atp_show_all_lines exec 'setlocal efm+=%-P%*[^()]' elseif l:dont_ignore exec 'setlocal efm+=%-P%*[^()]' endif let &l:errorformat = &l:errorformat.", \%".pm."Q)%r, \%".pm."Q%*[^()])%r, \%".pm."Q[%\\d%*[^()])%r" if g:atp_ignore_unmatched && !g:atp_show_all_lines let &l:errorformat = &l:errorformat.",%-Q%*[^()]" elseif l:dont_ignore let &l:errorformat = &l:errorformat.",%-Q%*[^()]" endif " removed after GType " \%-G\ ...%.%#, endif endfunction "}}} "{{{ s:ShowErrors " each argument can be a word in flags as for s:SetErrorFormat (except the " word 'whole') + two other flags: all (include all errors) and ALL (include " all errors and don't ignore any line - this overrides the variables " g:atp_ignore_unmatched and g:atp_show_all_lines. function! ShowErrors(...) let errorfile = &l:errorfile " read the log file and merge warning lines " filereadable doesn't like shellescaped file names not fnameescaped. " The same for readfile() and writefile() built in functions. if !filereadable( errorfile) echohl WarningMsg echomsg "No error file: " . errorfile echohl Normal return endif let l:log=readfile(errorfile) let l:nr=1 for l:line in l:log if l:line =~ "LaTeX Warning:" && l:log[l:nr] !~ "^$" let l:newline=l:line . l:log[l:nr] let l:log[l:nr-1]=l:newline call remove(l:log,l:nr) endif let l:nr+=1 endfor call writefile(l:log, errorfile) " set errorformat let l:arg = ( a:0 > 0 ? a:1 : "e" ) if l:arg =~ 'o' OpenLog return endif call s:SetErrorFormat(l:arg) let l:show_message = ( a:0 >= 2 ? a:2 : 1 ) " read the log file cg " final stuff if len(getqflist()) == 0 if l:show_message echomsg "no errors" endif return ":)" else cl return 1 endif endfunction "}}} if !exists("*ListErrorsFlags") function! ListErrorsFlags(A,L,P) return "all\nc\ne\nF\nf\nfi\no\nr\nw" endfunction endif "}}} endif "}}} " Commands: " {{{ command! -buffer -nargs=? ViewOutput :call ViewOutput() command! -buffer SyncTex :call SyncTex() command! -buffer PID :call GetPID() command! -buffer -bang MakeLatex :call MakeLatex(( g:atp_RelativePath ? globpath(b:atp_ProjectDir, fnamemodify(b:atp_MainFile, ":t")) : b:atp_MainFile ), 0,0, [],1,1,,1) command! -buffer -nargs=? -bang -count=1 -complete=customlist,TEX_Comp TEX :call TeX(, , ) command! -buffer -count=1 DTEX :call TeX(, , 'debug') command! -buffer -bang -nargs=? Bibtex :call Bibtex(, ) command! -buffer -nargs=? SetErrorFormat :call SetErrorFormat() command! -buffer -nargs=? SetErrorFormat :call SetErrorFormat() command! -buffer -nargs=? -complete=custom,ListErrorsFlags ShowErrors :call ShowErrors() " }}} " vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1 ftplugin/ATP_files/mappings.vim [[[1 479 " Author: Marcin Szmotulski " Description: This file contains mappings defined by ATP. " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " Language: tex " Last Change: " Commands to library functions (autoload/atplib.vim) command! -buffer -bang -nargs=* FontSearch :call atplib#FontSearch(, ) command! -buffer -bang -nargs=* FontPreview :call atplib#FontPreview(,) command! -buffer -nargs=1 -complete=customlist,atplib#Fd_completion OpenFdFile :call atplib#OpenFdFile() command! -buffer -nargs=* CloseLastEnvironment :call atplib#CloseLastEnvironment() command! -buffer CloseLastBracket :call atplib#CloseLastBracket() let g:atp_map_list = [ \ [ g:atp_map_forward_motion_leader, 'i', ':NInput', 'nmap ' ], \ [ g:atp_map_backward_motion_leader, 'i', ':NPnput', 'nmap ' ], \ [ g:atp_map_forward_motion_leader, 'gf', ':NInput', 'nmap ' ], \ [ g:atp_map_backward_motion_leader, 'gf', ':NPnput', 'nmap ' ], \ [ g:atp_map_forward_motion_leader, 'S', 'GotoNextSubSection', 'nmap ' ], \ [ g:atp_map_backward_motion_leader, 'S', 'vGotoNextSubSection', 'nmap ' ], \ ] " Add maps, unless the user didn't want them. if ( !exists("g:no_plugin_maps") || exists("g:no_plugin_maps") && g:no_plugin_maps == 0 ) && \ ( !exists("g:no_atp_maps") || exists("g:no_plugin_maps") && g:no_atp_maps == 0 ) nmap t SyncTexKeyStroke nmap SyncTexKeyStroke nmap ]* :SkipCommentForward omap ]* :SkipCommentForward nmap gc :SkipCommentForward omap gc :SkipCommentForward vmap ]* SkipCommentForward vmap gc SkipCommentForward vmap gC SkipCommentBackward vmap [* SkipCommentBackward nmap [* :SkipCommentBackward omap [* :SkipCommentBackward nmap gC :SkipCommentBackward omap gC :SkipCommentBackward execute "nmap ".g:atp_map_forward_motion_leader."i :NInput" execute "nmap ".g:atp_map_backward_motion_leader."i :PInput" execute "nmap ".g:atp_map_forward_motion_leader."gf :NInput" execute "nmap ".g:atp_map_backward_motion_leader."gf :PInput" " Syntax motions: " imap TexSyntaxMotionForward " imap TexSyntaxMotionBackward " nmap TexSyntaxMotionForward " nmap TexSyntaxMotionBackward imap TexJMotionForward imap TexJMotionBackward nmap TexJMotionForward nmap TexJMotionBackward if g:atp_map_forward_motion_leader == "}" noremap }} } endif if g:atp_map_backward_motion_leader == "{" noremap {{ { endif " ToDo to doc. + vmaps! execute "nmap ".g:atp_map_forward_motion_leader."S GotoNextSubSection" execute "vmap ".g:atp_map_forward_motion_leader."S vGotoNextSubSection" execute "nmap ".g:atp_map_backward_motion_leader."S GotoPreviousSubSection" execute "vmap ".g:atp_map_backward_motion_leader."S vGotoPreviousSubSection" " Toggle this maps on/off! execute "nmap ".g:atp_map_forward_motion_leader."s GotoNextSection" execute "vmap ".g:atp_map_forward_motion_leader."s vGotoNextSection" execute "nmap ".g:atp_map_backward_motion_leader."s GotoPreviousSection" execute "vmap ".g:atp_map_backward_motion_leader."s vGotoPreviousSection" if !( g:atp_map_forward_motion_leader == "]" && &l:diff ) execute "nmap ".g:atp_map_forward_motion_leader."c GotoNextChapter" execute "vmap ".g:atp_map_forward_motion_leader."c vGotoNextChapter" endif if !( g:atp_map_backward_motion_leader == "]" && &l:diff ) execute "nmap ".g:atp_map_backward_motion_leader."c GotoPreviousChapter" execute "vmap ".g:atp_map_backward_motion_leader."c vGotoPreviousChapter" endif execute "nmap ".g:atp_map_forward_motion_leader."p GotoNextPart" execute "vmap ".g:atp_map_forward_motion_leader."p vGotoNextPart" execute "nmap ".g:atp_map_backward_motion_leader."p GotoPreviousPart" execute "vmap ".g:atp_map_backward_motion_leader."p vGotoPreviousPart" execute "map ".g:atp_map_forward_motion_leader."e GotoNextEnvironment" execute "map ".g:atp_map_backward_motion_leader."e GotoPreviousEnvironment" " exe "map ".g:atp_map_forward_motion_leader." GotoNextEnvironment" " exe "map ".g:atp_map_backward_motion_leader." GotoPreviousEnvironment" " map ]m GotoNextInlineMath " map [m GotoPreviousInlineMath execute "map ".g:atp_map_forward_motion_leader."m GotoNextMath" execute "map ".g:atp_map_backward_motion_leader."m GotoPreviousMath" execute "map ".g:atp_map_forward_motion_leader."M GotoNextDisplayedMath" execute "map ".g:atp_map_backward_motion_leader."M GotoPreviousDisplayedMath" " Goto File Map: if has("path_extra") nnoremap gf :call GotoFile("", "") endif if exists("g:atp_no_tab_map") && g:atp_no_tab_map == 1 imap =atplib#TabCompletion(1) nnoremap :call atplib#TabCompletion(1,1) imap =atplib#TabCompletion(0) nnoremap :call atplib#TabCompletion(0,1) else " the default: imap =atplib#TabCompletion(1) imap =atplib#TabCompletion(0) " HOW TO: do this with ? Streightforward solution interacts with " other maps (e.g. after \l this map is called). " when this is set it also runs after the \l map: ?!? " nmap :call atplib#TabCompletion(1,1) nnoremap :call atplib#TabCompletion(0,1) vnoremap :WrapSelection '\{','}','begin' endif " Fonts: execute "vnoremap ".g:atp_vmap_text_font_leader."f :WrapSelection '{\\usefont{".g:atp_font_encoding."}{}{}{}\\selectfont ', '}', '".(len(g:atp_font_encoding)+11)."'" execute "vnoremap ".g:atp_vmap_text_font_leader."mb :WrapSelection '\\mbox{', '}', 'begin'" execute "vnoremap ".g:atp_vmap_text_font_leader."te :InteligentWrapSelection ['\\textrm{'],['\\text{']" execute "vnoremap ".g:atp_vmap_text_font_leader."rm :InteligentWrapSelection ['\\textrm{'],['\\mathrm{']" execute "vnoremap ".g:atp_vmap_text_font_leader."em :InteligentWrapSelection ['\\emph{'],['\\mathit{']" " Suggested Maps: " execute "vnoremap ".g:atp_vmap_text_font_leader."tx :InteligentWrapSelection [''],['\\text{']" " execute "vnoremap ".g:atp_vmap_text_font_leader."in :InteligentWrapSelection [''],['\\intertext{']" execute "vnoremap ".g:atp_vmap_text_font_leader."it :InteligentWrapSelection ['\\textit{'],['\\mathit{']" execute "vnoremap ".g:atp_vmap_text_font_leader."sf :InteligentWrapSelection ['\\textsf{'],['\\mathsf{']" execute "vnoremap ".g:atp_vmap_text_font_leader."tt :InteligentWrapSelection ['\\texttt{'],['\\mathtt{']" execute "vnoremap ".g:atp_vmap_text_font_leader."bf :InteligentWrapSelection ['\\textbf{'],['\\mathbf{']" execute "vnoremap ".g:atp_vmap_text_font_leader."bb :InteligentWrapSelection ['\\textbf{'],['\\mathbb{']" execute "vnoremap ".g:atp_vmap_text_font_leader."sl :WrapSelection '\\textsl{'" execute "vnoremap ".g:atp_vmap_text_font_leader."sc :WrapSelection '\\textsc{'" execute "vnoremap ".g:atp_vmap_text_font_leader."up :WrapSelection '\\textup{'" execute "vnoremap ".g:atp_vmap_text_font_leader."md :WrapSelection '\\textmd{'" execute "vnoremap ".g:atp_vmap_text_font_leader."un :WrapSelection '\\underline{'" execute "vnoremap ".g:atp_vmap_text_font_leader."ov :WrapSelection '\\overline{'" execute "vnoremap ".g:atp_vmap_text_font_leader."no :InteligentWrapSelection ['\\textnormal{'],['\\mathnormal{']" execute "vnoremap ".g:atp_vmap_text_font_leader."cal :InteligentWrapSelection [''],['\\mathcal{']" " Environments: execute "vnoremap ".g:atp_vmap_environment_leader."C :WrapSelection '"."\\"."begin{center}','"."\\"."end{center}','0','1'" execute "vnoremap ".g:atp_vmap_environment_leader."R :WrapSelection '"."\\"."begin{flushright}','"."\\"."end{flushright}','0','1'" execute "vnoremap ".g:atp_vmap_environment_leader."L :WrapSelection '"."\\"."begin{flushleft}','"."\\"."end{flushleft}','0','1'" execute "vnoremap ".g:atp_vmap_environment_leader."E :WrapSelection '"."\\"."begin{equation=g:atp_StarMathEnvDefault}','"."\\"."end{equation=g:atp_StarMathEnvDefault}','0','1'" execute "vnoremap ".g:atp_vmap_environment_leader."A :WrapSelection '"."\\"."begin{align=g:atp_StarMathEnvDefault}','"."\\"."end{align=g:atp_StarMathEnvDefault}','0','1'" " Math Modes: vmap m :WrapSelection '\(', '\)' vmap M :WrapSelection '\[', '\]' " Brackets: execute "vnoremap ".g:atp_vmap_bracket_leader."( :WrapSelection '(', ')', 'begin'" execute "vnoremap ".g:atp_vmap_bracket_leader."[ :WrapSelection '[', ']', 'begin'" execute "vnoremap ".g:atp_vmap_bracket_leader."\\{ :WrapSelection '\\{', '\\}', 'begin'" execute "vnoremap ".g:atp_vmap_bracket_leader."{ :WrapSelection '{', '}', 'begin'" " execute "vnoremap ".g:atp_vmap_bracket_leader."{ :InteligentWrapSelection ['{', '}'],['\\{', '\\}']" execute "vnoremap ".g:atp_vmap_bracket_leader.") :WrapSelection '(', ')', 'end'" execute "vnoremap ".g:atp_vmap_bracket_leader."] :WrapSelection '[', ']', 'end'" execute "vnoremap ".g:atp_vmap_bracket_leader."\\} :WrapSelection '\\{', '\\}', 'end'" execute "vnoremap ".g:atp_vmap_bracket_leader."} :WrapSelection '{', '}', 'end'" execute "vnoremap ".g:atp_vmap_big_bracket_leader."( :WrapSelection '\\left(', '\\right)', 'begin'" execute "vnoremap ".g:atp_vmap_big_bracket_leader."[ :WrapSelection '\\left[', '\\right]', 'begin'" execute "vnoremap ".g:atp_vmap_big_bracket_leader."{ :WrapSelection '\\left\\{','\\right\\}', 'begin'" " for compatibility: execute "vnoremap ".g:atp_vmap_big_bracket_leader."\\{ :WrapSelection '\\left\\{','\\right\\}', 'begin'" execute "vnoremap ".g:atp_vmap_big_bracket_leader.") :WrapSelection '\\left(', '\\right)', 'end'" execute "vnoremap ".g:atp_vmap_big_bracket_leader."] :WrapSelection '\\left[', '\\right]', 'end'" execute "vnoremap ".g:atp_vmap_big_bracket_leader."} :WrapSelection '\\left\\{', '\\right\\}', 'end'" " for compatibility: execute "vnoremap ".g:atp_vmap_big_bracket_leader."\\} :WrapSelection '\\left\\{', '\\right\\}', 'end'" " Tex Align: nmap a :TexAlign " Paragraph Selecting: vmap ip ATP_SelectCurrentParagraphInner vmap ap ATP_SelectCurrentParagraphOuter omap ip :normal vip omap ap :normal vap " Formating: nmap gw m`vipgq`` " Indent: nmap g> m`vip>`` nmap g< m`vip<`` nmap 2g> m`vip2>`` nmap 2g< m`vip2<`` nmap 3g> m`vip3>`` nmap 3g< m`vip3<`` nmap 4g> m`vip4>`` nmap 4g< m`vip4<`` nmap 5g> m`vip5>`` nmap 5g< m`vip5<`` nmap 6g> m`vip6>`` nmap 6g< m`vip6<`` vmap aS SelectOuterSyntax vmap iS SelectInnerSyntax " From vim.vim plugin (by Bram Mooleaner) " Move around functions. nnoremap [[ m':call search('\\begin\s*{\\|\\\@ vnoremap [[ m':exe "normal! gv"call search('\\begin\s*{\\|\\\@ nnoremap ]] m':call search('\\begin\s*{\\|\\\@ vnoremap ]] m':exe "normal! gv"call search('\\begin\s*{\\|\\\@ nnoremap [] m':call search('\\end\s*{\\|\\\@ vnoremap [] m':exe "normal! gv"call search('\\end\s*{\\|\\\@ nnoremap ][ m':call search('\\end\s*{\\|\\\@ vnoremap ][ m':exe "normal! gv"call search('\\end\s*{\\|\\\@ " Move around comments nnoremap ]% :call search('^\(\s*%.*\n\)\@ vnoremap ]% :exe "normal! gv"call search('^\(\s*%.*\n\)\@ nnoremap [% :call search('\%(^\s*%.*\n\)\%(^\s*%\)\@!', "bW") vnoremap [% :exe "normal! gv"call search('\%(^\s*%.*\n\)\%(^\s*%\)\@!', "bW") " Select comment vmap sc vSelectComment " Normal mode maps (mostly) nmap v ATP_ViewOutput nmap ToggleSpace nmap s ToggleStar " Todo: to doc: nmap D ToggleDebugMode nmap ChangeEnv nmap ToggleEnvForward " nmap ToggleEnvBackward nmap LatexEnvPrompt " ToDo: " if g:atp_LatexBox " nmap :call ChangeEnv() " endif nmap ATP_ViewOutput imap ATP_ViewOutput nmap g Getpid nmap t ATP_TOC nmap L ATP_Labels nmap l ATP_TeXCurrent nmap d ATP_TeXDebug "ToDo: imaps! nmap ATP_TeXVerbose nmap ToggleAuTeX imap ToggleAuTeXa nmap ` ToggleTab imap ` ToggleTab nmap B SimpleBibtex nmap b BibtexDefault nmap d Delete imap d Deletea nmap l OpenLog imap l OpenLog " nmap e :cf nnoremap :ShowErrors e inoremap e :ShowErrors e nnoremap w :ShowErrors w inoremap w :ShowErrors w nnoremap r :ShowErrors rc nnoremap r :ShowErrors rc nnoremap f :ShowErrors f inoremap f :ShowErrors f nnoremap g PdfFonts nnoremap :TexDoc inoremap :TexDoc " nmap pr SshPrint " FONT MAPPINGS if g:atp_imap_first_leader == "]" || g:atp_imap_second_leader == "]" || g:atp_imap_third_leader == "]" || g:atp_imap_fourth_leader == "]" inoremap ]] ] endif " execute 'imap '.g:atp_imap_second_leader.'rm \textrm{}' execute 'inoremap ' .g:atp_imap_second_leader.'rm :call Insert("\\textrm{", "\\mathrm{")a' execute 'inoremap ' .g:atp_imap_second_leader.'up \textup{}' execute 'inoremap ' .g:atp_imap_second_leader.'md \textmd{}' " execute 'inoremap ' .g:atp_imap_second_leader.'it \textit{}' execute 'inoremap ' .g:atp_imap_second_leader.'it :call Insert("\\textit{", "\\mathit{")a' execute 'inoremap ' .g:atp_imap_second_leader.'sl \textsl{}' execute 'inoremap ' .g:atp_imap_second_leader.'sc \textsc{}' " execute 'inoremap ' .g:atp_imap_second_leader.'sf \textsf{}' execute 'inoremap ' .g:atp_imap_second_leader.'sf :call Insert("\\textsf{", "\\mathsf{")a' " execute 'inoremap ' .g:atp_imap_second_leader.'bf \textbf{}' execute 'inoremap ' .g:atp_imap_second_leader.'bf :call Insert("\\textbf{", "\\mathbf{")a' " execute 'inoremap ' .g:atp_imap_second_leader.'tt \texttt{}' execute 'inoremap ' .g:atp_imap_second_leader.'tt :call Insert("\\texttt{", "\\mathtt{")a' execute 'inoremap ' .g:atp_imap_second_leader.'em \emph{}' execute 'inoremap ' .g:atp_imap_second_leader.'no :call Insert("\\textnormal{", "\\mathnormal{")a' " execute 'inoremap ' .g:atp_imap_second_leader.'mit \mathit{}' " execute 'inoremap ' .g:atp_imap_second_leader.'mrm \mathrm{}' " execute 'inoremap ' .g:atp_imap_second_leader.'msf \mathsf{}' " execute 'inoremap ' .g:atp_imap_second_leader.'mbf \mathbf{}' execute 'inoremap ' .g:atp_imap_second_leader.'bb \mathbb{}' " execute 'imap ' .g:atp_imap_second_leader.'mtt \mathtt{}' execute 'inoremap ' .g:atp_imap_second_leader.'cal \mathcal{}' " GREEK LETTERS execute 'imap '.g:atp_imap_first_leader.'a \alpha' execute 'imap '.g:atp_imap_first_leader.'b \beta' execute 'imap '.g:atp_imap_first_leader.'c \chi' execute 'imap '.g:atp_imap_first_leader.'d \delta' execute 'imap '.g:atp_imap_first_leader.'e \epsilon' execute 'imap '.g:atp_imap_first_leader.'ve \varepsilon' execute 'imap '.g:atp_imap_first_leader.'f \phi' execute 'imap '.g:atp_imap_first_leader.'y \psi' execute 'imap '.g:atp_imap_first_leader.'g \gamma' execute 'imap '.g:atp_imap_first_leader.'h \eta' execute 'imap '.g:atp_imap_first_leader.'k \kappa' execute 'imap '.g:atp_imap_first_leader.'l \lambda' execute 'imap '.g:atp_imap_first_leader.'i \iota' execute 'imap '.g:atp_imap_first_leader.'m \mu' execute 'imap '.g:atp_imap_first_leader.'n \nu' execute 'imap '.g:atp_imap_first_leader.'p \pi' execute 'imap '.g:atp_imap_first_leader.'o \theta' execute 'imap '.g:atp_imap_first_leader.'r \rho' execute 'imap '.g:atp_imap_first_leader.'s \sigma' execute 'imap '.g:atp_imap_first_leader.'t \tau' execute 'imap '.g:atp_imap_first_leader.'u \upsilon' execute 'imap '.g:atp_imap_first_leader.'vs \varsigma' execute 'imap '.g:atp_imap_first_leader.'vo \vartheta' execute 'imap '.g:atp_imap_first_leader.'w \omega' execute 'imap '.g:atp_imap_first_leader.'x \xi' execute 'imap '.g:atp_imap_first_leader.'z \zeta' execute 'imap '.g:atp_imap_first_leader.'D \Delta' execute 'imap '.g:atp_imap_first_leader.'Y \Psi' execute 'imap '.g:atp_imap_first_leader.'F \Phi' execute 'imap '.g:atp_imap_first_leader.'G \Gamma' execute 'imap '.g:atp_imap_first_leader.'L \Lambda' execute 'imap '.g:atp_imap_first_leader.'M \Mu' execute 'imap '.g:atp_imap_first_leader.'N \Nu' execute 'imap '.g:atp_imap_first_leader.'P \Pi' execute 'imap '.g:atp_imap_first_leader.'O \Theta' execute 'imap '.g:atp_imap_first_leader.'S \Sigma' execute 'imap '.g:atp_imap_first_leader.'T \Tau' execute 'imap '.g:atp_imap_first_leader.'U \Upsilon' execute 'imap '.g:atp_imap_first_leader.'W \Omega' execute 'imap '.g:atp_imap_first_leader.'Z \mathrm{Z}' let infty_leader = (g:atp_imap_first_leader == "#" ? "_" : g:atp_imap_first_leader ) execute 'imap '.infty_leader.'8 \infty' execute 'imap '.g:atp_imap_first_leader.'& \wedge' execute 'imap '.g:atp_imap_first_leader.'+ \bigcup' execute 'imap '.g:atp_imap_first_leader.'- \setminus' if g:atp_no_env_maps != 1 if g:atp_env_maps_old == 1 execute 'imap '.g:atp_imap_third_leader.'b \begin{}' execute 'imap '.g:atp_imap_third_leader.'e \end{}' execute 'imap '.g:atp_imap_third_leader.'c \begin{center}\end{center}O' execute 'imap '.g:atp_imap_fourth_leader.'c \begin{=g:atp_EnvNameCorollary=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{=g:atp_EnvNameCorollary=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_third_leader.'d \begin{=g:atp_EnvNameDefinition=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{=g:atp_EnvNameDefinition=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_fourth_leader.'u \begin{enumerate}'.g:atp_EnvOptions_enumerate.'\end{enumerate}O\item' execute 'imap '.g:atp_imap_third_leader.'a \begin{align=(getline(".")[col(".")-2]=="*"?"":g:atp_StarMathEnvDefault)}\end{align=(getline(".")[col(".")-2]=="*"?"":g:atp_StarMathEnvDefault)}O' execute 'imap '.g:atp_imap_third_leader.'i \item' execute 'imap '.g:atp_imap_fourth_leader.'i \begin{itemize}'.g:atp_EnvOptions_itemize.'\end{itemize}O\item' execute 'imap '.g:atp_imap_third_leader.'l \begin{=g:atp_EnvNameLemma=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{=g:atp_EnvNameLemma=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_fourth_leader.'p \begin{proof}\end{proof}O' execute 'imap '.g:atp_imap_third_leader.'p \begin{=g:atp_EnvNameProposition=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{=g:atp_EnvNameProposition=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_third_leader.'t \begin{=g:atp_EnvNameTheorem=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{=g:atp_EnvNameTheorem=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_fourth_leader.'t \begin{center}\begin{tikzpicture}\end{tikzpicture}\end{center}' if g:atp_extra_env_maps == 1 execute 'imap '.g:atp_imap_third_leader.'r \begin{=g:atp_EnvNameRemark=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{=g:atp_EnvNameRemark=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_fourth_leader.'l \begin{flushleft}\end{flushleft}O' execute 'imap '.g:atp_imap_third_leader.'r \begin{flushright}\end{flushright}O' execute 'imap '.g:atp_imap_third_leader.'f \begin{frame}\end{frame}O' execute 'imap '.g:atp_imap_fourth_leader.'q \begin{equation=(getline(".")[col(".")-2]=="*"?"":g:atp_StarMathEnvDefault)}\end{equation=(getline(".")[col(".")-2]=="*"?"":g:atp_StarMathEnvDefault)}O' execute 'imap '.g:atp_imap_third_leader.'n \begin{=g:atp_EnvNameNote=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{=g:atp_EnvNameNote=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_third_leader.'o \begin{=g:atp_EnvNameObservation=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{=g:atp_EnvNameObservation=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_third_leader.'x \begin{example=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{example=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' endif else " New mapping for the insert mode. execute 'imap '.g:atp_imap_third_leader.'b \begin{}' execute 'imap '.g:atp_imap_third_leader.'e \end{}' execute 'imap '.g:atp_imap_third_leader.'t \begin{=g:atp_EnvNameTheorem=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{=g:atp_EnvNameTheorem=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_third_leader.'d \begin{=g:atp_EnvNameDefinition=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{=g:atp_EnvNameDefinition=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_third_leader.'P \begin{=g:atp_EnvNameProposition=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{=g:atp_EnvNameProposition=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_third_leader.'l \begin{=g:atp_EnvNameLemma=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{=g:atp_EnvNameLemma=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_third_leader.'r \begin{=g:atp_EnvNameRemark=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{=g:atp_EnvNameRemark=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_third_leader.'C \begin{=g:atp_EnvNameCorollary=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{=g:atp_EnvNameCorollary=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_third_leader.'p \begin{proof}\end{proof}O' execute 'imap '.g:atp_imap_third_leader.'x \begin{example=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{example=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_third_leader.'n \begin{=g:atp_EnvNameNote=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{=g:atp_EnvNameNote=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_third_leader.'E \begin{enumerate}'.g:atp_EnvOptions_enumerate.'\end{enumerate}O\item' execute 'imap '.g:atp_imap_third_leader.'I \begin{itemize}'.g:atp_EnvOptions_itemize.'\end{itemize}O\item' execute 'imap '.g:atp_imap_third_leader.'i :call InsertItem()a' execute 'imap '.g:atp_imap_third_leader.'a \begin{align=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{align=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_third_leader.'q \begin{equation=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}\end{equation=(getline(".")[col(".")-2]=="*"?"":g:atp_StarEnvDefault)}O' execute 'imap '.g:atp_imap_third_leader.'c \begin{center}\end{center}O' execute 'imap '.g:atp_imap_third_leader.'L \begin{flushleft}\end{flushleft}O' execute 'imap '.g:atp_imap_third_leader.'R \begin{flushright}\end{flushright}O' execute 'imap '.g:atp_imap_third_leader.'T \begin{center}\begin{tikzpicture}\end{tikzpicture}\end{center}O' execute 'imap '.g:atp_imap_third_leader.'f \begin{frame}\end{frame}O' endif " imap }c \begin{corollary*}\end{corollary*}O " imap }d \begin{definition*}\end{definition*}O " imap }x \begin{example*}\normalfont\end{example*}O " imap }l \begin{lemma*}\end{lemma*}O " imap }n \begin{note*}\end{note*}O " imap }o \begin{observation*}\end{observation*}O " imap }p \begin{proposition*}\end{proposition*}O " imap }r \begin{remark*}\end{remark*}O " imap }t \begin{theorem*}\end{theorem*}O endif " Taken from AucTex: " Typing __ results in _{} function! SubBracket() let s:insert = "_" let s:left = getline(line("."))[col(".")-2] if s:left == '_' let s:insert = "{}\" endif return s:insert endfunction if g:atp_imap_first_leader == "_" || g:atp_imap_first_leader == "_" || \ g:atp_imap_third_leader == "_" || g:atp_imap_fourth_leader == "_" imap __ _{} else inoremap _ =SubBracket() endif " Taken from AucTex: " Typing ^^ results in ^{} function! SuperBracket() let s:insert = "^" let s:left = getline(line("."))[col(".")-2] if s:left == '^' let s:insert = "{}\" endif return s:insert endfunction if g:atp_imap_first_leader == "_" || g:atp_imap_first_leader == "_" || \ g:atp_imap_third_leader == "_" || g:atp_imap_fourth_leader == "_" imap ^^ ^{} else inoremap ^ =SuperBracket() endif " function! Infty() " let g:insert = g:atp_imap_first_leader " let g:left = getline(line("."))[col(".")-2] " if g:left == g:atp_imap_first_leader " let g:insert = "\\infty" " let g:new_line = strpart(getline("."),0 ,col(".")) . g:insert . strpart(getline("."), col(".")) " call setline(line("."), g:new_line) " echomsg "new_line:" . g:new_line " else " normal a " endif " echomsg "col:" . col(".") . " insert:" . g:insert . " left:" . g:left " return g:insert " endfunction " execute "inoremap 8 :call Infty()" execute "imap ".g:atp_imap_third_leader."m \\(\\)" execute "imap ".g:atp_imap_third_leader."M \\[\\]" endif " vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1 ftplugin/ATP_files/abbreviations.vim [[[1 174 " Author: Marcin Szmotulski " Description: This file contains abbreviations defined in ATP. " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " Language: tex " Last Change: if exists("g:atp_noabbreviations") && g:atp_noabbreviations == 1 finish endif iabbrev +- \pm iabbrev +\| \dagger iabbrev ++ \ddagger " LaTeX Environments if empty(maparg(g:atp_iabbrev_leader . "document" . g:atp_iabbrev_leader, "i", 1)) execute "iabbrev ".g:atp_iabbrev_leader."document".g:atp_iabbrev_leader." \begin{document}\end{document}O" endif if empty(maparg(g:atp_iabbrev_leader . "description" . g:atp_iabbrev_leader, "i", 1)) execute "iabbrev ".g:atp_iabbrev_leader."description".g:atp_iabbrev_leader." \begin{description}\end{description}O" endif if empty(maparg(g:atp_iabbrev_leader . "letter" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'letter'.g:atp_iabbrev_leader.' \begin{letter}\end{letter}O' endif if empty(maparg(g:atp_iabbrev_leader . "picture" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'picture'.g:atp_iabbrev_leader.' \begin{picture}()()\end{picture}f(a' endif if empty(maparg(g:atp_iabbrev_leader . "list" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'list'.g:atp_iabbrev_leader.' \begin{list}\end{list}O' endif if empty(maparg(g:atp_iabbrev_leader . "minipage" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'minipage'.g:atp_iabbrev_leader.' \begin{minipage}\end{minipage}A' endif if empty(maparg(g:atp_iabbrev_leader . "titlepage" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'titlepage'.g:atp_iabbrev_leader.' \begin{titlepage}\end{titlepage}O' endif if empty(maparg(g:atp_iabbrev_leader . "bibliography" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'bibliography'.g:atp_iabbrev_leader.' \begin{thebibliography}\end{thebibliography}A' endif if empty(maparg(g:atp_iabbrev_leader . "thebibliography" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'thebibliography'.g:atp_iabbrev_leader.' \begin{thebibliography}\end{thebibliography}A' endif if empty(maparg(g:atp_iabbrev_leader . "center" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'center'.g:atp_iabbrev_leader.' \begin{center}\end{center}O' endif if empty(maparg(g:atp_iabbrev_leader . "flushright" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'flushright'.g:atp_iabbrev_leader.' \begin{flushright}\end{flushright}O' endif if empty(maparg(g:atp_iabbrev_leader . "flushleft" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'flushleft'.g:atp_iabbrev_leader.' \begin{flushleft}\end{flushleft}O' endif if empty(maparg(g:atp_iabbrev_leader . "tikzpicture" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'tikzpicture'.g:atp_iabbrev_leader.' \begin{tikzpicture}\end{tikzpicture}O' endif if empty(maparg(g:atp_iabbrev_leader . "frame" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'frame'.g:atp_iabbrev_leader.' \begin{frame}\end{frame}O' endif if empty(maparg(g:atp_iabbrev_leader . "itemize" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'itemize'.g:atp_iabbrev_leader.' \begin{itemize}\end{itemize}O' endif if empty(maparg(g:atp_iabbrev_leader . "enumerate" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'enumerate'.g:atp_iabbrev_leader.' \begin{enumerate}\end{enumerate}O' endif if empty(maparg(g:atp_iabbrev_leader . "quote" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'quote'.g:atp_iabbrev_leader.' \begin{quote}\end{quote}O' endif if empty(maparg(g:atp_iabbrev_leader . "quotation" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'quotation'.g:atp_iabbrev_leader.' \begin{quotation}\end{quotation}O' endif if empty(maparg(g:atp_iabbrev_leader . "verse" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'verse'.g:atp_iabbrev_leader.' \begin{verse}\end{verse}O' endif if empty(maparg(g:atp_iabbrev_leader . "abstract" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'abstract'.g:atp_iabbrev_leader.' \begin{abstract}\end{abstract}O' endif if empty(maparg(g:atp_iabbrev_leader . "verbatim" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'verbatim'.g:atp_iabbrev_leader.' \begin{verbatim}\end{verbatim}O' endif if empty(maparg(g:atp_iabbrev_leader . "figure" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'figure'.g:atp_iabbrev_leader.' \begin{figure}\end{figure}O' endif if empty(maparg(g:atp_iabbrev_leader . "array" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'array'.g:atp_iabbrev_leader.' \begin{array}\end{array}O' endif if empty(maparg(g:atp_iabbrev_leader . "table" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'table'.g:atp_iabbrev_leader.' \begin{table}\end{table}O' endif if empty(maparg(g:atp_iabbrev_leader . "tabular" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'tabular'.g:atp_iabbrev_leader.' \begin{tabular}\end{tabular}A' endif " AMS Stuff if empty(maparg(g:atp_iabbrev_leader . "equation" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'equation'.g:atp_iabbrev_leader.' \begin{equation}\end{equation}O' endif if empty(maparg(g:atp_iabbrev_leader . "equation\\*" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'equation*'.g:atp_iabbrev_leader.' \begin{equation*}\end{equation*}O' endif if empty(maparg(g:atp_iabbrev_leader . "align" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'align'.g:atp_iabbrev_leader.' \begin{align}\end{align}O' endif if empty(maparg(g:atp_iabbrev_leader . "align\\*" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'align*'.g:atp_iabbrev_leader.' \begin{align*}\end{align*}O' endif if empty(maparg(g:atp_iabbrev_leader . "alignat" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'alignat'.g:atp_iabbrev_leader.' \begin{alignat}\end{alignat}O' endif if empty(maparg(g:atp_iabbrev_leader . "alignat\\*" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'alignat*'.g:atp_iabbrev_leader.' \begin{alignat*}\end{alignat*}O' endif if empty(maparg(g:atp_iabbrev_leader . "gather" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'gather'.g:atp_iabbrev_leader.' \begin{gather}\end{gather}O' endif if empty(maparg(g:atp_iabbrev_leader . "gather\\*" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'gather*'.g:atp_iabbrev_leader.' \begin{gather*}\end{gather*}O' endif if empty(maparg(g:atp_iabbrev_leader . "multline" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'multline'.g:atp_iabbrev_leader.' \begin{multline}\end{multline}O' endif if empty(maparg(g:atp_iabbrev_leader . "multline\\*" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'multline*'.g:atp_iabbrev_leader.' \begin{multline*}\end{multline*}O' endif if empty(maparg(g:atp_iabbrev_leader . "split" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'split'.g:atp_iabbrev_leader.' \begin{split}\end{split}O' endif if empty(maparg(g:atp_iabbrev_leader . "flalign" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'flalign'.g:atp_iabbrev_leader.' \begin{flalign}\end{flalign}O' endif if empty(maparg(g:atp_iabbrev_leader . "flalign\\*" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'flalign*'.g:atp_iabbrev_leader.' \begin{flalign*}\end{flalign*}O' endif " Local Environments if !exists("g:atp_LocalEnvironments") call LocalCommands() endif for env in b:atp_LocalEnvironments if !empty(maparg(g:atp_iabbrev_leader.env.g:atp_iabbrev_leader, "i", 1)) " silent echomsg "abbreviation " . g:atp_iabbrev_leader.env.g:atp_iabbrev_leader . " exists." continue endif if exists("g:atp_abbreviate_".env) execute "iabbrev ".g:atp_iabbrev_leader.env.g:atp_iabbrev_leader." \\begin{".env."}".get(g:atp_abbreviate_{env}, 0, "")."\\end{".env."}".get(g:atp_abbreviate_{env}, 1, "O") else execute "iabbrev ".g:atp_iabbrev_leader.env.g:atp_iabbrev_leader." \\begin{".env."}\\end{".env."}O" endif endfor if empty(maparg(g:atp_iabbrev_leader . "corollary" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'corollary'.g:atp_iabbrev_leader.' \begin{corollary}\end{corollary}O' endif if empty(maparg(g:atp_iabbrev_leader . "theorem" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'theorem'.g:atp_iabbrev_leader.' \begin{theorem}\end{theorem}O' endif if empty(maparg(g:atp_iabbrev_leader . "proposition" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'proposition'.g:atp_iabbrev_leader.' \begin{proposition}\end{proposition}O' endif if empty(maparg(g:atp_iabbrev_leader . "lemma" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'lemma'.g:atp_iabbrev_leader.' \begin{lemma}\end{lemma}O' endif if empty(maparg(g:atp_iabbrev_leader . "definition" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'definition'.g:atp_iabbrev_leader.' \begin{definition}\end{definition}O' endif if empty(maparg(g:atp_iabbrev_leader . "proof" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'proof'.g:atp_iabbrev_leader.' \begin{proof}\end{proof}O' endif if empty(maparg(g:atp_iabbrev_leader . "remark" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'remark'.g:atp_iabbrev_leader.' \begin{remark}\end{remark}O' endif if empty(maparg(g:atp_iabbrev_leader . "example" . g:atp_iabbrev_leader, "i", 1)) execute 'iabbrev '.g:atp_iabbrev_leader.'example'.g:atp_iabbrev_leader.' \begin{example}\end{example}O' endif ftplugin/ATP_files/menu.vim [[[1 254 " Author: Marcin Szamotulski " Description: This file sets up the menu. " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " Language: tex " Last Change: let s:sourced = ( !exists("s:sourced") ? 0 : 1 ) if s:sourced finish endif let Compiler = get(g:CompilerMsg_Dict, matchstr(b:atp_TexCompiler, '^\s*\zs\S*'), 'Compile') let Viewer = get(g:ViewerMsg_Dict, matchstr(b:atp_Viewer, '^\s*\zs\S*'), "") if !exists("no_plugin_menu") && !exists("no_atp_menu") execute "menu 550.5 LaTe&X.&".Compiler.":TEX :TEX" execute "cmenu 550.5 LaTe&X.&".Compiler.":TEX TEX" execute "imenu 550.5 LaTe&X.&".Compiler.":TEX :TEXa" execute "menu 550.6 LaTe&X.".Compiler."\\ debug:TEX\\ debug :DTEX" execute "cmenu 550.6 LaTe&X.".Compiler."\\ debug:TEX\\ debug DTEX" execute "imenu 550.6 LaTe&X.".Compiler."\\ debug:TEX\\ debug :DTEXa" execute "menu 550.7 LaTe&X.".Compiler."\\ &twice:2TEX :2TEX" execute "cmenu 550.7 LaTe&X.".Compiler."\\ &twice:2TEX 2TEX" execute "imenu 550.7 LaTe&X.".Compiler."\\ &twice:2TEX :2TEXa" nmenu 550.8 LaTe&X.&MakeLatex:MakeLatex :MakeLatex cmenu 550.8 LaTe&X.&MakeLatex:MakeLatex MakeLatex imenu 550.8 LaTe&X.&MakeLatex:MakeLatex :MakeLatexa menu 550.9 LaTe&X.&Bibtex:Bibtex :Bibtex cmenu 550.9 LaTe&X.&Bibtex:Bibtex Bibtex imenu 550.9 LaTe&X.&Bibtex:Bibtex :Bibtexa if Viewer != "" execute "menu 550.10 LaTe&X.&View\\ with\\ ".Viewer.":ViewOutput :ViewOutput" execute "cmenu 550.10 LaTe&X.&View\\ with\\ ".Viewer.":ViewOutput ViewOutput" execute "imenu 550.10 LaTe&X.&View\\ with\\ ".Viewer.":ViewOutput :ViewOutputa" else execute "menu 550.10 LaTe&X.&View\\ Output:ViewOutput :ViewOutput" execute "cmenu 550.10 LaTe&X.&View\\ Output:ViewOutput ViewOutput" execute "imenu 550.10 LaTe&X.&View\\ Output:ViewOutput :ViewOutputa" endif " menu 550.20.1 LaTe&X.&Errors:ShowErrors :ShowErrors cmenu 550.20.1 LaTe&X.&Errors:ShowErrors ShowErrors imenu 550.20.1 LaTe&X.&Errors:ShowErrors :ShowErrors menu 550.20.1 LaTe&X.&Log.&Open\ Log\ File:ShowErrors\ o :ShowErrors\ o cmenu 550.20.1 LaTe&X.&Log.&Open\ Log\ File:ShowErrors\ o ShowErrors\ o imenu 550.20.1 LaTe&X.&Log.&Open\ Log\ File:ShowErrors\ o :ShowErrors\ o if t:atp_DebugMode == "debug" menu 550.20.5 LaTe&X.&Log.Toggle\ &Debug\ Mode\ [on] :ToggleDebugMode cmenu 550.20.5 LaTe&X.&Log.Toggle\ &Debug\ Mode\ [on] ToggleDebugMode imenu 550.20.5 LaTe&X.&Log.Toggle\ &Debug\ Mode\ [on] :ToggleDebugModea else menu 550.20.5 LaTe&X.&Log.Toggle\ &Debug\ Mode\ [off] :ToggleDebugMode cmenu 550.20.5 LaTe&X.&Log.Toggle\ &Debug\ Mode\ [off] ToggleDebugMode imenu 550.20.5 LaTe&X.&Log.Toggle\ &Debug\ Mode\ [off] :ToggleDebugModea endif menu 550.20.20 LaTe&X.&Log.-ShowErrors- : menu 550.20.20 LaTe&X.&Log.&Warnings:ShowErrors\ w :ShowErrors w cmenu 550.20.20 LaTe&X.&Log.&Warnings:ShowErrors\ w ShowErrors w imenu 550.20.20 LaTe&X.&Log.&Warnings:ShowErrors\ w :ShowErrors w menu 550.20.20 LaTe&X.&Log.&Citation\ Warnings:ShowErrors\ c :ShowErrors c cmenu 550.20.20 LaTe&X.&Log.&Citation\ Warnings:ShowErrors\ c ShowErrors c imenu 550.20.20 LaTe&X.&Log.&Citation\ Warnings:ShowErrors\ c :ShowErrors c menu 550.20.20 LaTe&X.&Log.&Reference\ Warnings:ShowErrors\ r :ShowErrors r cmenu 550.20.20 LaTe&X.&Log.&Reference\ Warnings:ShowErrors\ r ShowErrors r imenu 550.20.20 LaTe&X.&Log.&Reference\ Warnings:ShowErrors\ r :ShowErrors r menu 550.20.20 LaTe&X.&Log.&Font\ WarningsShowErrors\ f :ShowErrors f cmenu 550.20.20 LaTe&X.&Log.&Font\ WarningsShowErrors\ f ShowErrors f imenu 550.20.20 LaTe&X.&Log.&Font\ WarningsShowErrors\ f :ShowErrors f menu 550.20.20 LaTe&X.&Log.Font\ Warnings\ &&\ Info:ShowErrors\ fi :ShowErrors fi cmenu 550.20.20 LaTe&X.&Log.Font\ Warnings\ &&\ Info:ShowErrors\ fi ShowErrors fi imenu 550.20.20 LaTe&X.&Log.Font\ Warnings\ &&\ Info:ShowErrors\ fi :ShowErrors fi menu 550.20.20 LaTe&X.&Log.&Show\ Files:ShowErrors\ F :ShowErrors F cmenu 550.20.20 LaTe&X.&Log.&Show\ Files:ShowErrors\ F ShowErrors F imenu 550.20.20 LaTe&X.&Log.&Show\ Files:ShowErrors\ F :ShowErrors F " menu 550.20.20 LaTe&X.&Log.-PdfFotns- : menu 550.20.20 LaTe&X.&Log.&Pdf\ Fonts:PdfFonts :PdfFonts cmenu 550.20.20 LaTe&X.&Log.&Pdf\ Fonts:PdfFonts PdfFonts imenu 550.20.20 LaTe&X.&Log.&Pdf\ Fonts:PdfFonts :PdfFonts menu 550.20.20 LaTe&X.&Log.-Delete- : menu 550.20.20 LaTe&X.&Log.&Delete\ Tex\ Output\ Files:Delete :Delete cmenu 550.20.20 LaTe&X.&Log.&Delete\ Tex\ Output\ Files:Delete Delete imenu 550.20.20 LaTe&X.&Log.&Delete\ Tex\ Output\ Files:Delete :Delete menu 550.20.20 LaTe&X.&Log.Set\ Error\ File:SetErrorFile :SetErrorFile cmenu 550.20.20 LaTe&X.&Log.Set\ Error\ File:SetErrorFile SetErrorFile imenu 550.20.20 LaTe&X.&Log.Set\ Error\ File:SetErrorFile :SetErrorFilea " menu 550.25 LaTe&X.-Print- : menu 550.26 LaTe&X.&SshPrint:SshPrint :SshPrint cmenu 550.26 LaTe&X.&SshPrint:SshPrint SshPrint imenu 550.26 LaTe&X.&SshPrint:SshPrint :SshPrinta " menu 550.30 LaTe&X.-TOC- : menu 550.30 LaTe&X.&Table\ of\ Contents:TOC :TOC cmenu 550.30 LaTe&X.&Table\ of\ Contents:TOC TOC imenu 550.30 LaTe&X.&Table\ of\ Contents:TOC :TOC menu 550.30 LaTe&X.L&abels:Labels :Labels cmenu 550.30 LaTe&X.L&abels:Labels Labels imenu 550.30 LaTe&X.L&abels:Labels :Labels " menu 550.40 LaTe&X.&Go\ to.&GotoFile:GotoFile :GotoFile cmenu 550.40 LaTe&X.&Go\ to.&GotoFile:GotoFile GotoFile imenu 550.40 LaTe&X.&Go\ to.&GotoFile:GotoFile :GotoFile " menu 550.40 LaTe&X.&Go\ to.-Environment- : menu 550.40 LaTe&X.&Go\ to.Next\ Definition:NEnv\ definition :NEnv definition cmenu 550.40 LaTe&X.&Go\ to.Next\ Definition:NEnv\ definition NEnv definition imenu 550.40 LaTe&X.&Go\ to.Next\ Definition:NEnv\ definition :NEnv definition menu 550.40 LaTe&X.&Go\ to.Previuos\ Definition:PEnv\ definition :PEnv definition cmenu 550.40 LaTe&X.&Go\ to.Previuos\ Definition:PEnv\ definition PEnv definition imenu 550.40 LaTe&X.&Go\ to.Previuos\ Definition:PEnv\ definition :PEnv definition menu 550.40 LaTe&X.&Go\ to.Next\ Environment:NEnv\ [pattern] :NEnv cmenu 550.40 LaTe&X.&Go\ to.Next\ Environment:NEnv\ [pattern] NEnv imenu 550.40 LaTe&X.&Go\ to.Next\ Environment:NEnv\ [pattern] :NEnv menu 550.40 LaTe&X.&Go\ to.Previuos\ Environment:PEnv\ [pattern] :PEnv cmenu 550.40 LaTe&X.&Go\ to.Previuos\ Environment:PEnv\ [pattern] PEnv imenu 550.40 LaTe&X.&Go\ to.Previuos\ Environment:PEnv\ [pattern] :PEnv " menu 550.40 LaTe&X.&Go\ to.-Section- : menu 550.40 LaTe&X.&Go\ to.&Next\ Section:NSec :NSec cmenu 550.40 LaTe&X.&Go\ to.&Next\ Section:NSec NSec imenu 550.40 LaTe&X.&Go\ to.&Next\ Section:NSec :NSec menu 550.40 LaTe&X.&Go\ to.&Previuos\ Section:PSec :PSec cmenu 550.40 LaTe&X.&Go\ to.&Previuos\ Section:PSec PSec imenu 550.40 LaTe&X.&Go\ to.&Previuos\ Section:PSec :PSec menu 550.40 LaTe&X.&Go\ to.Next\ Chapter:NChap :NChap cmenu 550.40 LaTe&X.&Go\ to.Next\ Chapter:NChap NChap imenu 550.40 LaTe&X.&Go\ to.Next\ Chapter:NChap :NChap menu 550.40 LaTe&X.&Go\ to.Previous\ Chapter:PChap :PChap cmenu 550.40 LaTe&X.&Go\ to.Previous\ Chapter:PChap PChap imenu 550.40 LaTe&X.&Go\ to.Previous\ Chapter:PChap :PChap menu 550.40 LaTe&X.&Go\ to.Next\ Part:NPart :NPart cmenu 550.40 LaTe&X.&Go\ to.Next\ Part:NPart NPart imenu 550.40 LaTe&X.&Go\ to.Next\ Part:NPart :NPart menu 550.40 LaTe&X.&Go\ to.Previuos\ Part:PPart :PPart cmenu 550.40 LaTe&X.&Go\ to.Previuos\ Part:PPart PPart imenu 550.40 LaTe&X.&Go\ to.Previuos\ Part:PPart :PPart " menu 550.50 LaTe&X.-Bib- : menu 550.50 LaTe&X.Bib\ Search:Bibsearch\ [pattern] :BibSearch cmenu 550.50 LaTe&X.Bib\ Search:Bibsearch\ [pattern] BibSearch imenu 550.50 LaTe&X.Bib\ Search:Bibsearch\ [pattern] :BibSearch menu 550.50 LaTe&X.Input\ Files:InputFiles :InputFiles cmenu 550.50 LaTe&X.Input\ Files:InputFiles InputFiles imenu 550.50 LaTe&X.Input\ Files:InputFiles :InputFiles " menu 550.60 LaTe&X.-Viewer- : menu 550.60 LaTe&X.Set\ &XPdf\ (forward\ search):SetXpdf :SetXpdf cmenu 550.60 LaTe&X.Set\ &XPdf\ (forward\ search):SetXpdf SetXpdf imenu 550.60 LaTe&X.Set\ &XPdf\ (forward\ search):SetXpdf :SetXpdf menu 550.60 LaTe&X.Set\ &Okular\ (forward\/reverse\ search):SetOkular :SetOkular cmenu 550.60 LaTe&X.Set\ &Okular\ (forward\/reverse\ search):SetOkular SetOkular imenu 550.60 LaTe&X.Set\ &Okular\ (forward\/reverse\ search):SetOkular :SetOkular menu 550.60 LaTe&X.Set\ X&Dvi\ (forward\/reverse\ search):SetXdvi :SetXdvi cmenu 550.60 LaTe&X.Set\ X&Dvi\ (forward\/reverse\ search):SetXdvi SetXdvi imenu 550.60 LaTe&X.Set\ X&Dvi\ (forward\/reverse\ search):SetXdvi :SetXdvi " menu 550.70 LaTe&X.-Editting- : " " ToDo: show options doesn't work from the menu (it disappears immediately, but at " some point I might change it completely) menu 550.70 LaTe&X.&Options.&Show\ Options:ShowOptions[!] :ShowOptions cmenu 550.70 LaTe&X.&Options.&Show\ Options:ShowOptions[!] ShowOptions imenu 550.70 LaTe&X.&Options.&Show\ Options:ShowOptions[!] :ShowOptions if g:atp_callback menu 550.70 LaTe&X.&Options.Toggle\ &Call\ Back\ [on]g:atp_callback :ToggleCallBack cmenu 550.70 LaTe&X.&Options.Toggle\ &Call\ Back\ [on]g:atp_callback ToggleCallBack imenu 550.70 LaTe&X.&Options.Toggle\ &Call\ Back\ [on]g:atp_callback :ToggleCallBacka else menu 550.70 LaTe&X.&Options.Toggle\ &Call\ Back\ [off]g:atp_callback :ToggleCallBack cmenu 550.70 LaTe&X.&Options.Toggle\ &Call\ Back\ [off]g:atp_callback ToggleCallBack imenu 550.70 LaTe&X.&Options.Toggle\ &Call\ Back\ [off]g:atp_callback :ToggleCallBacka endif menu 550.70 LaTe&X.&Options.-set\ options- : " There is menu for ToggleAuTeX " menu 550.70 LaTe&X.&Options.Automatic\ TeX\ Processingb:atp_autex :let b:atp_autex= " imenu 550.70 LaTe&X.&Options.Automatic\ TeX\ Processingb:atp_autex :let b:atp_autex= menu 550.70 LaTe&X.&Options.Set\ TeX\ Compiler:Compiler :Compiler cmenu 550.70 LaTe&X.&Options.Set\ TeX\ Compiler:Compiler Compiler imenu 550.70 LaTe&X.&Options.Set\ TeX\ Compiler:Compiler :Compiler menu 550.70 LaTe&X.&Options.Set\ Debug\ Mode:DebugMode\ {mode} :DebugMode cmenu 550.70 LaTe&X.&Options.Set\ Debug\ Mode:DebugMode\ {mode} DebugMode imenu 550.70 LaTe&X.&Options.Set\ Debug\ Mode:Compiler\ {compiler} :DebugMode menu 550.70 LaTe&X.&Options.Set\ Runsb:atp_auruns :let b:atp_auruns= cmenu 550.70 LaTe&X.&Options.Set\ Runsb:atp_auruns let b:atp_auruns= imenu 550.70 LaTe&X.&Options.Set\ Runsb:atp_auruns :let b:atp_auruns= menu 550.70 LaTe&X.&Options.Set\ Viewer:Viewer\ {viewer} :Viewer cmenu 550.70 LaTe&X.&Options.Set\ Viewer:Viewer\ {viewer} Viewer imenu 550.70 LaTe&X.&Options.Set\ Viewer:Viewer\ {viewer} :Viewer menu 550.70 LaTe&X.&Options.Set\ Output\ Directoryb:atp_OutDir :let b:atp_ViewerOptions=" cmenu 550.70 LaTe&X.&Options.Set\ Output\ Directoryb:atp_OutDir let b:atp_ViewerOptions=" imenu 550.70 LaTe&X.&Options.Set\ Output\ Directoryb:atp_OutDir :let b:atp_ViewerOptions=" menu 550.70 LaTe&X.&Options.Set\ Output\ Directory\ to\ the\ default\ value:SetOutDir :SetOutDir cmenu 550.70 LaTe&X.&Options.Set\ Output\ Directory\ to\ the\ default\ value:SetOutDir SetOutDir imenu 550.70 LaTe&X.&Options.Set\ Output\ Directory\ to\ the\ default\ value:SetOutDir :SetOutDir " The title is misleading! I think it is not needed here. " menu 550.70 LaTe&X.&Options.Ask\ for\ the\ Output\ Directoryg:askfortheoutdir :let g:askfortheoutdir=" " imenu 550.70 LaTe&X.&Options.Ask\ for\ the\ Output\ Directoryg:askfortheoutdir :let g:askfortheoutdir=" menu 550.70 LaTe&X.&Options.Set\ Error\ File:SetErrorFile :SetErrorFile cmenu 550.70 LaTe&X.&Options.Set\ Error\ File:SetErrorFile SetErrorFile imenu 550.70 LaTe&X.&Options.Set\ Error\ File:SetErrorFile :SetErrorFile menu 550.70 LaTe&X.&Options.Which\ TeX\ files\ to\ copyg:keep :let g:keep=" cmenu 550.70 LaTe&X.&Options.Which\ TeX\ files\ to\ copyg:keep let g:keep=" imenu 550.70 LaTe&X.&Options.Which\ TeX\ files\ to\ copyg:keep :let g:keep=" menu 550.70 LaTe&X.&Options.Tex\ extensionsg:atp_tex_extensions :let g:atp_tex_extensions=" cmenu 550.70 LaTe&X.&Options.Tex\ extensionsg:atp_tex_extensions let g:atp_tex_extensions=" imenu 550.70 LaTe&X.&Options.Tex\ extensionsg:atp_tex_extensions :let g:atp_tex_extensions=" menu 550.70 LaTe&X.&Options.Remove\ Commandg:rmcommand :let g:rmcommand=" cmenu 550.70 LaTe&X.&Options.Remove\ Commandg:rmcommand let g:rmcommand=" imenu 550.70 LaTe&X.&Options.Remove\ Commandg:rmcommand :let g:rmcommand=" menu 550.70 LaTe&X.&Options.Default\ Bib\ Flagsg:defaultbibflags :let g:defaultbibflags=" cmenu 550.70 LaTe&X.&Options.Default\ Bib\ Flagsg:defaultbibflags let g:defaultbibflags=" imenu 550.70 LaTe&X.&Options.Default\ Bib\ Flagsg:defaultbibflags :let g:defaultbibflags=" " if b:atp_autex menu 550.75 &LaTeX.&Toggle\ AuTeX\ [on]b:atp_autex :ToggleAuTeX cmenu 550.75 &LaTeX.&Toggle\ AuTeX\ [on]b:atp_autex ToggleAuTeX imenu 550.75 &LaTeX.&Toggle\ AuTeX\ [on]b:atp_autex :ToggleAuTeXa else menu 550.75 &LaTeX.&Toggle\ AuTeX\ [off]b:atp_autex :ToggleAuTeX cmenu 550.75 &LaTeX.&Toggle\ AuTeX\ [off]b:atp_autex ToggleAuTeX imenu 550.75 &LaTeX.&Toggle\ AuTeX\ [off]b:atp_autex :ToggleAuTeXa endif menu 550.78 LaTe&X.&Toggle\ Space\ [off]cmap\ \ \\_s\\+ :ToggleSpace cmenu 550.78 LaTe&X.&Toggle\ Space\ [off]cmap\ \ \\_s\\+ ToggleSpace imenu 550.78 LaTe&X.&Toggle\ Space\ [off]cmap\ \ \\_s\\+ :ToggleSpacea tmenu LaTe&X.&Toggle\ Space\ [off] cmap \_s\+ is curently off " ToggleNn menu is made by s:LoadHistory if g:atp_mapNn menu 550.79 LaTe&X.Toggle\ &Nn\ [on]:ToggleNn :ToggleNn cmenu 550.79 LaTe&X.Toggle\ &Nn\ [on]:ToggleNn ToggleNn imenu 550.79 LaTe&X.Toggle\ &Nn\ [on]:ToggleNn :ToggleNna tmenu LaTeX.Toggle\ Nn\ [on] n,N vim normal commands. else menu 550.79 LaTe&X.Toggle\ &Nn\ [off]:ToggleNn :ToggleNn cmenu 550.79 LaTe&X.Toggle\ &Nn\ [off]:ToggleNn ToggleNn imenu 550.79 LaTe&X.Toggle\ &Nn\ [off]:ToggleNn :ToggleNna tmenu LaTeX.Toggle\ Nn\ [off] atp maps to n,N. endif if g:atp_MathOpened menu 550.80 LaTe&X.Toggle\ &Check\ if\ in\ Math\ [on]g:atp_MathOpened :ToggleCheckMathOpened cmenu 550.80 LaTe&X.Toggle\ &Check\ if\ in\ Math\ [on]g:atp_MathOpened ToggleCheckMathOpened imenu 550.80 LaTe&X.Toggle\ &Check\ if\ in\ Math\ [on]g:atp_MathOpened :ToggleCheckMathOpeneda else menu 550.80 LaTe&X.Toggle\ &Check\ if\ in\ Math\ [off]g:atp_MathOpened :ToggleCheckMathOpened cmenu 550.80 LaTe&X.Toggle\ &Check\ if\ in\ Math\ [off]g:atp_MathOpened ToggleCheckMathOpened imenu 550.80 LaTe&X.Toggle\ &Check\ if\ in\ Math\ [off]g:atp_MathOpened :ToggleCheckMathOpeneda endif endif " vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1 ftplugin/ATP_files/motion.vim [[[1 1537 " Author: Marcin Szamotulski " Description: This file contains motion and highlight functions of ATP. " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " Language: tex " Last Change: let s:sourced = ( !exists("s:sourced") ? 0 : 1 ) " Functions: (source once) if !s:sourced || g:atp_reload_functions "{{{ " All table of contents stuff: variables, functions and commands. " {{{ Table Of Contents " {{{2 Variabels let g:atp_sections={ \ 'chapter' : [ '\m^\s*\(\\chapter\*\?\s*{\)', '\m\\chapter\*'], \ 'section' : [ '\m^\s*\(\\section\*\?\s*{\)', '\m\\section\*'], \ 'subsection' : [ '\m^\s*\(\\subsection\*\?\s*{\)', '\m\\subsection\*'], \ 'subsubsection' : [ '\m^\s*\(\\subsubsection\*\?\s*{\)', '\m\\subsubsection\*'], \ 'bibliography' : ['\m^\s*\(\\begin\s*{\s*thebibliography\s*}\|\\bibliography\s*{\)' , 'nopattern'], \ 'abstract' : ['\m^\s*\(\\begin\s*{abstract}\|\\abstract\s*{\)', 'nopattern'], \ 'part' : [ '\m^\s*\(\\part\*\?\s*{\)', '\m\\part\*']} "--Make TOC ----------------------------- " This makes sense only for latex documents. " " Notes: Makeing toc from aux file: " + is fast " + one gets correct numbers " - one doesn't get line numbers " / the title might be modified thus one can not make a pattern " which works in all situations, while this is important for " :DeleteSection command / " " {{{2 s:find_toc_lines function! s:find_toc_lines() let toc_lines_nr=[] let toc_lines=[] let pos_saved=getpos(".") let pos=[0,1,1,0] keepjumps call setpos(".",pos) " Pattern: let j=0 for section in keys(g:atp_sections) if j == 0 let pattern=g:atp_sections[section][0] . '' else let pattern=pattern . '\|' . g:atp_sections[section][0] endif let j+=1 endfor " Searching Loop: let line=search(pattern, 'W') while line call add(toc_lines_nr, line) let line=search(pattern, 'W') endwhile keepjumps call setpos(".", pos_saved) for line in toc_lines_nr call add(toc_lines, getline(line)) endfor return toc_lines endfunction " {{{2 s:maketoc " this will store information: " { 'linenumber' : ['chapter/section/..', 'sectionnumber', 'section title', '0/1=not starred/starred'] } function! s:maketoc(filename) let toc={} " if the dictinary with labels is not defined, define it if !exists("t:atp_labels") let t:atp_labels = {} endif let texfile = [] " getbufline reads only loaded buffers, unloaded can be read from file. let bufname = fnamemodify(a:filename,":t") try let texfile = ( bufexists(bufname) ? getbufline("^" . bufname . "$","1","$") : readfile(a:filename) ) catch /E484:/ echohl Warning echo "File " . a:filename . " not readable." endtry let texfile_copy = deepcopy(texfile) let true = 1 let bline = 0 " We are not removing the preambule any more. let i = 1 " set variables for chapter/section numbers for section in keys(g:atp_sections) let ind{section} = 0 endfor " make a filter let j = 0 for section in keys(g:atp_sections) let filter = ( j == 0 ? g:atp_sections[section][0] . '' : filter . '\|' . g:atp_sections[section][0] ) let j+=1 endfor " ToDo: HOW TO MAKE THIS FAST? let s:filtered = filter(deepcopy(texfile), 'v:val =~ filter') for line in s:filtered for section in keys(g:atp_sections) if line =~ g:atp_sections[section][0] if line !~ '^\s*\\\@ empty set, but with " \chapter{title} --> title, solution: the name of " 'Abstract' will be plased, as we know what we have " matched let title = line " test if it is a starred version. let star=0 if g:atp_sections[section][1] != 'nopattern' && line =~ g:atp_sections[section][1] let star=1 else let star=0 endif " Problem: If there are two sections with the same title, this " does't work: let idx = index(texfile,line) call remove(texfile, idx) let i = idx let tline = i+bline+1 let bline +=1 " Find Title: let start = stridx(title,'{')+1 let title = strpart(title,start) " we are looking for the maching '}' let l:count = 1 let i=-1 while i<=len(title) let i+=1 if strpart(title,i,1) == '{' let l:count+=1 elseif strpart(title,i,1) == '}' let l:count-=1 endif if l:count == 0 break endif endwhile let title = strpart(title,0,i) " Section Number: " if it is not starred version add one to the section number " or it is not an abstract if star == 0 if !(section == 'chapter' && title =~ '^\cabstract$') let ind{section}+=1 endif endif if section == 'part' let indchapter = 0 let indsection = 0 let indsubsection = 0 let indsubsubsection = 0 elseif section == 'chapter' let indsection = 0 let indsubsection = 0 let indsubsubsection = 0 elseif section == 'section' let indsubsection = 0 let indsubsubsection = 0 elseif section == 'subsection' let indsubsubsection = 0 endif " Find Short Title: let shorttitle=line let start=stridx(shorttitle,'[')+1 if start == 0 let shorttitle='' else let shorttitle=strpart(shorttitle,start) " we are looking for the maching ']' let l:count=1 let i=-1 while i<=len(shorttitle) let i+=1 if strpart(shorttitle,i,1) == '[' let l:count+=1 elseif strpart(shorttitle,i,1) == ']' let l:count-=1 endif if l:count==0 break endif endwhile let shorttitle = strpart(shorttitle,0,i) endif "ToDo: if section is bibliography (using bib) then find the first " empty line: if section == "bibliography" && line !~ '\\begin\s*{\s*thebibliography\s*}' let idx = tline-1 while texfile_copy[idx] !~ '^\s*$' let idx-= 1 endwhile " " We add 1 as we want the first non blank line, and one more " " 1 as we want to know the line number not the list index " " number: let tline=idx+1 endif " Add results to the dictionary: call extend(toc, { tline : [ section, ind{section}, title, star, shorttitle] }) endif endif endfor endfor if exists("t:atp_toc") call extend(t:atp_toc, { a:filename : toc }, "force") else let t:atp_toc = { a:filename : toc } endif return t:atp_toc endfunction " {{{2 s:buflist if !exists("t:buflist") let t:buflist=[] endif function! s:buflist() " this names are used in TOC and passed to s:maketoc, which " makes a dictionary whose keys are the values of name defined " just below: let name=resolve(fnamemodify(bufname("%"),":p")) " add an entry to the list t:buflist if it is not there. if bufname("") =~ ".tex" && index(t:buflist,name) == -1 call add(t:buflist,name) endif return t:buflist endfunction " {{{2 RemoveFromBufList " function! RemoveFromBufList() " let i=1 " for f in t:buflist " echo "(" . i . ") " . f " let i+=1 " endfor " let which=input("Which file to remove (press for none)") " if which != "" && which =~ '\d\+' " call remove(t:buflist,f-1) " endif " endfunction " {{{2 s:showtoc function! s:showtoc(toc) " this is a dictionary of line numbers where a new file begins. let cline=line(".") " " Open new window or jump to the existing one. " " Remember the place from which we are coming: " let t:atp_bufname=bufname("") " let t:atp_winnr=winnr() these are already set by TOC() let bname="__ToC__" let tocwinnr=bufwinnr("^" . bname . "$") " echomsg "DEBUG a " . tocwinnr if tocwinnr != -1 " Jump to the existing window. exe tocwinnr . " wincmd w" silent exe "%delete" else " Open new window if its width is defined (if it is not the code below " will put toc in the current buffer so it is better to return. if !exists("t:toc_window_width") echoerr "t:toc_window_width not set" return endif let openbuffer="keepalt " . t:toc_window_width . "vsplit +setl\\ wiw=15\\ buftype=nofile\\ tabstop=1\\ filetype=toc_atp\\ nowrap __ToC__" keepalt silent exe openbuffer " We are setting the address from which we have come. silent call atplib#setwindow() endif let number=1 " this is the line number in ToC. " number is a line number relative to the file listed in ToC. " the current line number is linenumber+number " there are two loops: one over linenumber and the second over number. let numberdict = {} unlockvar b:atp_Toc let b:atp_Toc = {} " this variable will be used to set the cursor position in ToC. for openfile in keys(a:toc) call extend(numberdict, { openfile : number }) let part_on=0 let chap_on=0 let chnr=0 let secnr=0 let ssecnr=0 let sssecnr=0 let path=fnamemodify(bufname(""),":p:h") for line in keys(a:toc[openfile]) if a:toc[openfile][line][0] == 'chapter' let chap_on=1 break elseif a:toc[openfile][line][0] == 'part' let part_on=1 endif endfor let sorted = sort(keys(a:toc[openfile]), "atplib#CompareNumbers") let len = len(sorted) " write the file name in ToC (with a full path in paranthesis) call setline(number,fnamemodify(openfile,":t") . " (" . fnamemodify(openfile,":p:h") . ")") call extend(b:atp_Toc, { number : [ openfile, 1 ]}) let number+=1 for line in sorted call extend(b:atp_Toc, { number : [ openfile, line ] }) let lineidx=index(sorted,line) let nlineidx=lineidx+1 if nlineidx< len(sorted) let nline=sorted[nlineidx] else let nline=line("$") endif let lenght=len(line) if lenght == 0 let showline=" " elseif lenght == 1 let showline=" " . line elseif lenght == 2 let showline=" " . line elseif lenght == 3 let showline=" " . line elseif lenght == 4 let showline=" " . line elseif lenght>=5 let showline=line endif " Print ToC lines. if a:toc[openfile][line][0] == 'abstract' || a:toc[openfile][line][2] =~ '^\cabstract$' call setline(number, showline . "\t" . " " . "Abstract" ) elseif a:toc[openfile][line][0] =~ 'bibliography\|references' call setline (number, showline . "\t" . " " . a:toc[openfile][line][2]) elseif a:toc[openfile][line][0] == 'part' let partnr=a:toc[openfile][line][1] let nr=partnr if a:toc[openfile][line][3] "if it is stared version let nr=substitute(nr,'.',' ','') endif if a:toc[openfile][line][4] != '' " call setline (number, showline . "\t" . nr . " " . a:toc[openfile][line][4]) call setline (number, showline . "\t" . " " . a:toc[openfile][line][4]) else " call setline (number, showline . "\t" . nr . " " . a:toc[openfile][line][2]) call setline (number, showline . "\t" . " " . a:toc[openfile][line][2]) endif elseif a:toc[openfile][line][0] == 'chapter' let chnr=a:toc[openfile][line][1] let nr=chnr if a:toc[openfile][line][3] "if it is stared version let nr=substitute(nr,'.',' ','') endif if a:toc[openfile][line][4] != '' call setline (number, showline . "\t" . nr . " " . a:toc[openfile][line][4]) else call setline (number, showline . "\t" . nr . " " . a:toc[openfile][line][2]) endif elseif a:toc[openfile][line][0] == 'section' let secnr=a:toc[openfile][line][1] if chap_on let nr=chnr . "." . secnr if a:toc[openfile][line][3] "if it is stared version let nr=substitute(nr,'.',' ','g') endif if a:toc[openfile][line][4] != '' call setline (number, showline . "\t\t" . nr . " " . a:toc[openfile][line][4]) else call setline (number, showline . "\t\t" . nr . " " . a:toc[openfile][line][2]) endif else let nr=secnr if a:toc[openfile][line][3] "if it is stared version let nr=substitute(nr,'.',' ','g') endif if a:toc[openfile][line][4] != '' call setline (number, showline . "\t" . nr . " " . a:toc[openfile][line][4]) else call setline (number, showline . "\t" . nr . " " . a:toc[openfile][line][2]) endif endif elseif a:toc[openfile][line][0] == 'subsection' let ssecnr=a:toc[openfile][line][1] if chap_on let nr=chnr . "." . secnr . "." . ssecnr if a:toc[openfile][line][3] "if it is stared version let nr=substitute(nr,'.',' ','g') endif if a:toc[openfile][line][4] != '' call setline (number, showline . "\t\t\t" . nr . " " . a:toc[openfile][line][4]) else call setline (number, showline . "\t\t\t" . nr . " " . a:toc[openfile][line][2]) endif else let nr=secnr . "." . ssecnr if a:toc[openfile][line][3] "if it is stared version let nr=substitute(nr,'.',' ','g') endif if a:toc[openfile][line][4] != '' call setline (number, showline . "\t\t" . nr . " " . a:toc[openfile][line][4]) else call setline (number, showline . "\t\t" . nr . " " . a:toc[openfile][line][2]) endif endif elseif a:toc[openfile][line][0] == 'subsubsection' let sssecnr=a:toc[openfile][line][1] if chap_on let nr=chnr . "." . secnr . "." . sssecnr if a:toc[openfile][line][3] "if it is stared version let nr=substitute(nr,'.',' ','g') endif if a:toc[openfile][line][4] != '' call setline(number, a:toc[openfile][line][0] . "\t\t\t" . nr . " " . a:toc[openfile][line][4]) else call setline(number, a:toc[openfile][line][0] . "\t\t\t" . nr . " " . a:toc[openfile][line][2]) endif else let nr=secnr . "." . ssecnr . "." . sssecnr if a:toc[openfile][line][3] "if it is stared version let nr=substitute(nr,'.',' ','g') endif if a:toc[openfile][line][4] != '' call setline (number, showline . "\t\t" . nr . " " . a:toc[openfile][line][4]) else call setline (number, showline . "\t\t" . nr . " " . a:toc[openfile][line][2]) endif endif else let nr="" endif let number+=1 endfor endfor " set the cursor position on the correct line number. " first get the line number of the begging of the ToC of t:atp_bufname " (current buffer) " let t:numberdict=numberdict "DEBUG " t:atp_bufname is the full path to the current buffer. let num = get(numberdict, t:atp_bufname, 'no_number') if num == 'no_number' call s:TOC("") return endif let sorted = sort(keys(a:toc[t:atp_bufname]), "atplib#CompareNumbers") let t:sorted = sorted for line in sorted if cline>=line let num+=1 endif keepjumps call setpos('.',[bufnr(""),num,1,0]) endfor " Help Lines: if search(' jump and close', 'nW') == 0 call append('$', [ '', \ ' jump', \ ' jump and close', \ 's jump and split', \ 'y or c yank label', \ 'p paste label', \ 'q close', \ ':DeleteSection', \ ':PasteSection', \ ':SectionStack', \ ':Undo' ]) endif lockvar 3 b:atp_Toc endfunction "}}}2 " This is User Front End Function "{{{2 TOC function! TOC(bang) " skip generating t:atp_toc list if it exists and if a:0 != 0 if &l:filetype != 'tex' echoerr "Wrong 'filetype'. This command works only for latex documents." return endif " for each buffer in t:buflist (set by s:buflist) if ( a:bang == "!" || !exists("t:atp_toc") ) for buffer in t:buflist let t:atp_toc=s:maketoc(buffer) endfor endif call s:showtoc(t:atp_toc) endfunction nnoremap ATP_TOC :call TOC(1) " }}}2 " This finds the name of currently eddited section/chapter units. " {{{ Current TOC " ToDo: make this faster! " {{{ s:NearestSection " This function finds the section name of the current section unit with " respect to the dictionary a:section={ 'line number' : 'section name', ... } " it returns the [ section_name, section line, next section line ] function! NearestSection(section) let cline=line('.') let sorted=sort(keys(a:section), "atplib#CompareNumbers") let x=0 while x=1 && x < len(sorted) let section_name=a:section[sorted[x-1]] return [section_name, sorted[x-1], sorted[x]] elseif x>=1 && x >= len(sorted) let section_name=a:section[sorted[x-1]] return [section_name,sorted[x-1], line('$')] elseif x<1 && x < len(sorted) " if we are before the first section return the empty string return ['','0', sorted[x]] elseif x<1 && x >= len(sorted) return ['','0', line('$')] endif endfunction " }}} " {{{ s:ctoc function! s:ctoc() if &l:filetype != 'tex' " TO DO: " if exists(g:tex_flavor) " if g:tex_flavor != "latex" " echomsg "CTOC: Wrong 'filetype'. This function works only for latex documents." " endif " endif " Set the status line once more, to remove the CTOC() function. call ATPStatus("") return [] endif " resolve the full path: let t:atp_bufname=resolve(fnamemodify(bufname("%"),":p")) " if t:atp_toc(t:atp_bufname) exists use it otherwise make it if !exists("t:atp_toc") || !has_key(t:atp_toc,t:atp_bufname) silent let t:atp_toc=s:maketoc(t:atp_bufname) endif " l:count where the preambule ends let buffer=getbufline(bufname("%"),"1","$") let i=0 let line=buffer[0] while line !~ '\\begin\s*{document}' && i < len(buffer) let line=buffer[i] if line !~ '\\begin\s*{document}' let i+=1 endif endwhile " if we are before the '\\begin{document}' line: if line(".") <= i let return=['Preambule'] return return endif let chapter={} let section={} let subsection={} for key in keys(t:atp_toc[t:atp_bufname]) if t:atp_toc[t:atp_bufname][key][0] == 'chapter' " return the short title if it is provided if t:atp_toc[t:atp_bufname][key][4] != '' call extend(chapter, {key : t:atp_toc[t:atp_bufname][key][4]},'force') else call extend(chapter, {key : t:atp_toc[t:atp_bufname][key][2]},'force') endif elseif t:atp_toc[t:atp_bufname][key][0] == 'section' " return the short title if it is provided if t:atp_toc[t:atp_bufname][key][4] != '' call extend(section, {key : t:atp_toc[t:atp_bufname][key][4]},'force') else call extend(section, {key : t:atp_toc[t:atp_bufname][key][2]},'force') endif elseif t:atp_toc[t:atp_bufname][key][0] == 'subsection' " return the short title if it is provided if t:atp_toc[t:atp_bufname][key][4] != '' call extend(subsection, {key : t:atp_toc[t:atp_bufname][key][4]},'force') else call extend(subsection, {key : t:atp_toc[t:atp_bufname][key][2]},'force') endif endif endfor " Remove $ from chapter/section/subsection names to save the space. let chapter_name=substitute(s:NearestSection(chapter)[0],'\$','','g') let chapter_line=s:NearestSection(chapter)[1] let chapter_nline=s:NearestSection(chapter)[2] let section_name=substitute(s:NearestSection(section)[0],'\$','','g') let section_line=s:NearestSection(section)[1] let section_nline=s:NearestSection(section)[2] " let b:section=s:NearestSection(section) " DEBUG let subsection_name=substitute(s:NearestSection(subsection)[0],'\$','','g') let subsection_line=s:NearestSection(subsection)[1] let subsection_nline=s:NearestSection(subsection)[2] " let b:ssection=s:NearestSection(subsection) " DEBUG let names = [ chapter_name ] if (section_line+0 >= chapter_line+0 && section_line+0 <= chapter_nline+0) || chapter_name == '' call add(names, section_name) elseif subsection_line+0 >= section_line+0 && subsection_line+0 <= section_nline+0 call add(names, subsection_name) endif return names endfunction " }}} " {{{ CTOC function! CTOC(...) " if there is any argument given, then the function returns the value " (used by ATPStatus()), otherwise it echoes the section/subsection " title. It returns only the first b:atp_TruncateStatusSection " characters of the the whole titles. let names=s:ctoc() let chapter_name = get(names, 0, '') let section_name = get(names, 1, '') let subsection_name = get(names, 2, '') if chapter_name == "" && section_name == "" && subsection_name == "" if a:0 == '0' echo "" else return "" endif elseif chapter_name != "" if section_name != "" if a:0 != 0 return substitute(strpart(chapter_name,0,b:atp_TruncateStatusSection/2), '\_s*$', '','') . "/" . substitute(strpart(section_name,0,b:atp_TruncateStatusSection/2), '\_s*$', '','') endif else if a:0 != 0 return substitute(strpart(chapter_name,0,b:atp_TruncateStatusSection), '\_s*$', '','') endif endif elseif chapter_name == "" && section_name != "" if subsection_name != "" if a:0 != 0 return substitute(strpart(section_name,0,b:atp_TruncateStatusSection/2), '\_s*$', '','') . "/" . substitute(strpart(subsection_name,0,b:atp_TruncateStatusSection/2), '\_s*$', '','') endif else if a:0 != 0 return substitute(strpart(section_name,0,b:atp_TruncateStatusSection), '\_s*$', '','') endif endif elseif chapter_name == "" && section_name == "" && subsection_name != "" if a:0 != 0 return substitute(strpart(subsection_name,0,b:atp_TruncateStatusSection), '\_s*$', '','') endif endif endfunction " }}} " }}} " Labels Front End Finction. The search engine/show function are in autoload/atplib.vim script " library. " {{{ Labels " a:bang = "!" do not regenerate labels if not necessary function! Labels(bang) let t:atp_bufname = bufname("%") let error = len(getqflist()) let atp_MainFile = atplib#FullPath(b:atp_MainFile) " Generate the dictionary with labels if a:bang == "" || ( a:bang == "!" && !exists("t:atp_labels") ) let [ t:atp_labels, b:ListOfFiles ] = atplib#generatelabels(atp_MainFile, 1) endif " Show the labels in seprate window call atplib#showlabels([ t:atp_labels, map(copy(b:ListOfFiles), 'atplib#FullPath(v:val)')] ) if error echohl WarningMsg redraw echomsg "The compelation contains errors, aux file might be not appriopriate for labels window." echohl Normal endif endfunction nnoremap ATP_Labels :call Labels("") " }}} " GotoLabel & GotoLabelCompletion {{{ " a:bang = "!" do not regenerate labels if not necessary " This is developed for one tex project in a vim. function! GotoLabel(bang,...) let alabel = ( a:0 == 0 ? "" : a:1 ) let atp_MainFile = atplib#FullPath(b:atp_MainFile) " Generate the dictionary with labels if a:bang == "" || ( a:bang == "!" && ( !exists("b:ListOfFiles") || !exists("t:atp_labels") ) ) let [ t:atp_labels, b:ListOfFiles ] = atplib#generatelabels(atp_MainFile, 1) endif let matches = [] let g:matches=matches for file in keys(t:atp_labels) if index(b:ListOfFiles, fnamemodify(file, ":t")) != -1 || index(b:ListOfFiles, file) != -1 for label in t:atp_labels[file] if label[1] =~ alabel || label[2] =~ '^'.alabel call add(matches, extend([file], label)) endif endfor endif endfor if len(matches) == 0 redraw echohl WarningMsg echomsg "No matching label" echohl Normal return 1 elseif len(matches) == 1 let file=matches[0][0] let line=matches[0][1] else if len(keys(filter(copy(b:TypeDict), 'v:val == "input"'))) == 0 let mlabels=map(copy(matches), "['('.(index(matches, v:val)+1).')', v:val[2],v:val[3]]") let file=0 else let mlabels=map(copy(matches), "['('.(index(matches, v:val)+1).')', v:val[2], v:val[3], fnamemodify(v:val[0], ':t')]") let file=1 endif echohl Title echo "Which label to choose?" echohl Normal let mlabels= ( file ? extend([[' nr', 'LABEL', 'LABEL NR', 'FILE']], mlabels) : extend([[' nr', 'LABEL', 'LABEL NR']], mlabels) ) let nr = inputlist(atplib#Table(mlabels, [1,2,5]))-1 let file=matches[nr][0] let line=matches[nr][1] endif " Check if the buffer is loaded. if bufloaded(file) execute "b " . file call cursor(line,1) else execute "edit " . file call cursor(line,1) endif endfunction function! GotoLabelCompletion(ArgLead, CmdLine, CursorPos) let atp_MainFile = atplib#FullPath(b:atp_MainFile) " Generate the dictionary with labels (only if it doesn't exist) if !exists("t:atp_labels") || t:atp_labels == {} || !exists("b:ListOfFiles") let [ t:atp_labels, b:ListOfFiles ] = atplib#generatelabels(atp_MainFile, 1) endif let labels=[] for file in keys(t:atp_labels) if index(b:ListOfFiles, fnamemodify(file, ":t")) != -1 || index(b:ListOfFiles, file) != -1 call extend(labels, map(deepcopy(t:atp_labels)[file], 'v:val[1]')) call extend(labels, map(deepcopy(t:atp_labels)[file], 'v:val[2]')) endif endfor let g:labels=copy(labels) call filter(labels, "v:val !~ '^\s*$' && v:val =~ a:ArgLead ") return map(labels, "v:val.'\\>'") endfunction " }}} " Motion functions through environments and sections. " {{{ Motion functions " Go to next environment "{{{ " which name is given as the argument. Do not wrap " around the end of the file. function! GotoEnvironment(flag,...) " Options : let env_name = ( a:0 >= 1 && a:1 != "" ? a:1 : '[^}]*' ) " Set the search tool : if g:atp_mapNn let search_cmd = "S /" let search_cmd_e= "/ " . a:flag else let search_cmd = "call search('" let search_cmd_e= "','" . a:flag . "')" endif " Set the pattern : if env_name == 'math' let pattern = '\m\%(\(\\\@ 1 && " \ ( count(map(synstack(line("."),col(".")-1), 'synIDattr(v:val, "name")'), 'texMathZoneX') == 0 || " \ count(map(synstack(line("."),col(".")-1), 'synIDattr(v:val, "name")'), 'texMathZoneY') == 0 ) " silent call search(pattern, a:flag) " endif return "" endfunction "}}} " Go to next section {{{ " The extra argument is a pattern to match for the " section title. The first, obsolete argument stands for: " part,chapter,section,subsection,etc. " This commands wrap around the end of the file. " with a:3 = 'vim' it uses vim search() function " with a:3 = 'atp' " the default is: " if g:atp_mapNn then use 'atp' " else use 'vim'. function! GotoSection(bang, flag, secname, ...) let search_tool = ( a:0 >= 1 ? a:1 : ( g:atp_mapNn ? 'atp' : 'vim' ) ) let mode = ( a:0 >= 2 ? a:2 : 'n' ) let title_pattern = ( a:0 >= 3 ? a:3 : '' ) let pattern = ( empty(a:bang) ? '^\([^%]\|\\\@Input(flag) let pat = ( &l:filetype == "plaintex" ? '\\input\s*{' : '\%(\\input\>\|\\include\s*{\)' ) let @/ = '^\([^%]\|\\\@= 1 ? a:1 : strpart(getline("."), 0, col(".")) !~ '\(\\\@ method = "all" is used. let line = ( check_line ? getline(".") : "" ) if check_line let beg_line = strpart(line, 0,col(".")-1) " Find the begining columnt of the file name: let bcol = searchpos('\%({\|,\)', 'bn', line("."))[1] if bcol == 0 let bcol = searchpos('{', 'n', line("."))[1] endif " Find the end column of the file name let col = searchpos(',\|}', 'cn', line("."))[1] " Current column let cur_col = col(".") endif " DEBUG " let g:line = line " let g:file = a:file " let g:check_line = check_line " This part will be omitted if check_line is 0 (see note above). " \usepackege{...,,...} if line =~ '\\usepackage' && g:atp_developer let method = "usepackage" let ext = '.sty' let fname = atplib#append_ext(strpart(getline("."), bcol, col-bcol-1), ext) let file = atplib#KpsewhichFindFile('tex', fname, g:atp_texinputs, 1) let file_l = [ file ] " let file = get(file_l, 0, "file_missing") let message = "Pacakge: " let options = "" " \input{...}, \include{...} elseif line =~ '\\\(input\|include\)\s*{' let method = "input{" let ext = '.tex' " \input{} doesn't allow for {...,...} many file path. let fname = atplib#append_ext(strpart(getline("."), bcol, col-bcol-1), '.tex') " The 'file . ext' might be already a full path. if fnamemodify(fname, ":p") != fname let file_l = atplib#KpsewhichFindFile('tex', fname, g:atp_texinputs, -1, ':p', '^\(\/home\|\.\)', '\%(^\/usr\|kpsewhich\|texlive\|miktex\)') let file = get(file_l, 0, 'file_missing') else let file_l = [ fname ] let file = fname endif let message = "File: " let options = "" " \input /without {/ elseif line =~ '\\input\s*{\@!' let method = "input" let fname = atplib#append_ext(matchstr(getline(line(".")), '\\input\s*\zs\f*\ze'), '.tex') let file_l = atplib#KpsewhichFindFile('tex', fname, g:atp_texinputs, -1, ':p', '^\(\/home\|\.\)', '\%(^\/usr\|kpsewhich\|texlive\)') let file = get(file_l, 0, "file_missing") let options = ' +setl\ ft=' . &l:filetype " \documentclass{...} elseif line =~ '\\documentclass' && g:atp_developer let method = "documentclass" let saved_pos = getpos(".") call cursor(line("."), 1) call search('\\documentclass\zs', 'cb', line(".")) let bcol = searchpos('{', 'c', line("."))[1] execute "normal %" let ecol = col(".") call cursor(saved_pos[0], saved_pos[1]) let classname = strpart(getline("."), bcol, ecol-bcol-1) let fname = atplib#append_ext(classname, '.cls') let file = atplib#KpsewhichFindFile('tex', fname, g:atp_texinputs, ':p') let file_l = [ file ] let options = "" else " If not over any above give a list of input files to open, like " EditInputFile let method = "all" call extend(file_l, [ atp_MainFile ], 0) call extend(level_d, { atp_MainFile : 0 }) " call filter(file_l, "v:val !~ expand('%') . '$'") endif " DEBUG " let g:method = method " let g:file_l = file_l if len(file_l) > 1 && a:file =~ '^\s*$' if method == "all" let msg = "Which file to edit?" else let msg = "Found many files. Which file to use?" endif let mods = method == 'all' ? ":t" : ":p" " It is better to start numbering from 0, " then 0 - is the main file " 1 - is the first chapter, and so on. let i = 0 let input_l = [] for f in file_l if exists("level_d") let space = "" if g:atp_RelativePath let cwd = getcwd() exe "lcd " . fnameescape(b:atp_ProjectDir) let level = get(level_d,fnamemodify(f, ':.'), get(level_d, f, 1)) exe "lcd " . fnameescape(cwd) else let cwd = getcwd() exe "lcd " . fnameescape(b:atp_ProjectDir) let level = get(level_d,f, get(level_d,fnamemodify(f, ':.'), 1)) exe "lcd " . fnameescape(cwd) endif for j in range(level) let space .= " " endfor else space = "" endif call add(input_l, "(" . i . ") " . space . fnamemodify(f, mods)) let i+=1 endfor " Ask the user which file to edit: redraw if len([ msg ] + input_l) < &l:lines for f in [ msg ] + input_l " echo highlighted message if matchstr(f, '(\d\+)\s*\zs.*$') == expand("%:t") echohl CursorLine elseif f == msg echohl Title endif echo f if matchstr(f, '(\d\+)\s*\zs.*$') == expand("%:t") || f == msg echohl Normal endif endfor let choice = input("Type number and (empty cancels): ") if choice != "" let choice += 1 endif elseif for line in [ msg ] + input_l if line == msg echohl Title endif echo line echohl None endfor echohl MoreMsg let choice = input("Type number and (empty cancels): ") echohl None if choice != "" let choice += 1 endif endif " Remember: 0 == "" returns 1! " char2nr("") = 0 " nr2char(0) = "" if choice == "" exe "lcd " . fnameescape(cwd) return endif if choice < 1 || choice > len(file_l) if choice < 1 || choice > len(file_l) echo "\n" echoerr "Choice out of range." endif exe "lcd " . fnameescape(cwd) return endif let file = file_l[choice-1] let fname = file elseif a:file !~ '^\s*$' let file = atplib#FullPath(a:file) let fname = file endif " DEBUG " let g:fname = fname " let g:file = file " let g:file_l = file_l " let g:choice = choice if !exists("file") exe "lcd " . fnameescape(cwd) return endif if file != "file_missing" && filereadable(file) && ( !exists("choice") || exists("choice") && choice != 0 ) " Inherit tex flavour. " So that bib, cls, sty files will have their file type (bib/plaintex). let filetype = &l:filetype let old_file = expand("%:p") execute "edit " . fnameescape(file) if &l:filetype =~ 'tex$' && file =~ '\.tex$' && &l:filetype != filetype let &l:filetype = filetype " If the filetype is 'bib' we should source some portion of ATP, so " that if the bib file is changed tex will process that file " The best approach is to source only compiler.vim and add an " autocommand. " elseif &l:filetype == 'bib' " source ~/.vim/ftplugin/tex_atp.vim endif " Set the main file variable and pass the TreeOfFiles variables to the new " buffer. call RestoreProjectVariables(projectVarDict) let [ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ] = deepcopy([tree_d, file_l_orig, type_d, level_d ]) if !&l:autochdir exe "lcd " . fnameescape(cwd) endif return file else echohl ErrorMsg redraw if file != "file_missing" echo "File \'".fname."\' not found." else echo "Missing file." endif echohl None exe "lcd " . fnameescape(cwd) return file endif endfunction catch /E127:/ endtry function! GotoFileComplete(ArgLead, CmdLine, CursorPos) let bang = ( a:CmdLine =~ '^\w*!' ? '!' : '') if bang == "!" || !exists("b:TreeOfFiles") || !exists("b:ListOfFiles") || !exists("b:TypeDict") || !exists("b:LevelDict") let [tree_d, file_l, type_d, level_d ] = TreeOfFiles(atp_MainFile) else let [tree_d, file_l, type_d, level_d ] = deepcopy([ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ]) endif if index(file_l, b:atp_MainFile) == -1 || index(file_l, fnamemodify(b:atp_MailFile, ":p")) == -1 call add(file_l, b:atp_MainFile) endif return filter(file_l, "v:val =~ a:ArgLead") endfunction "}}} " Skip Comment "{{{ " a:flag=fb (f-forward, b-backward) " f works like ]* " b workd like [* " Note: the 's' search flag is passed by the associated commands. " This can be extended: " (1) skip empty lines between comments function! SkipComment(flag, mode, ...) let flag = ( a:flag =~ 'b' ? 'b' : '' ) let nr = ( a:flag =~ 'b' ? '-1' : 1 ) call search('^\zs\s*%', flag) call cursor(line("."), ( nr == -1 ? 1 : len(getline(line("."))))) let line = getline(line(".")) " find previous line let pline_nr=min([line("$"), max([1,line(".")+nr])]) let pline = getline(pline_nr) " This code find previous non empty line " while pline =~ '^\s*$' && pline_nr > 1 && pline_nr < line("$") " let pline_nr += nr " let pline=getline(pline_nr) " endwhile " while line =~ '^\s*%' || ( line =~ '^\s*$' && pline =~ '^\s*%' ) while pline =~ '^\s*%' call cursor(line(".")+nr, ( nr == -1 ? 1 : len(getline(line(".")+nr)))) " let line=getline(line(".")) let pline_nr=min([line("$"), max([1,line(".")+nr])]) let pline = getline(pline_nr) endwhile if a:mode == 'v' let end_pos = [ line("."), col(".") ] " Go where visual mode started exe "normal `" . ( nr == 1 ? '<' : '>' ) exe "normal " . visualmode() call cursor(end_pos) endif endfunction "}}} "}}} " Syntax motion " {{{ TexSyntaxMotion function! TexSyntaxMotion(forward, how, ...) " If the function is used in imap. let in_imap = ( a:0 >= 1 ? a:1 : 0 ) let whichwrap = split(&l:whichwrap, ',') if !count(whichwrap, 'l') setl ww+=l endif if !count(whichwrap, 'h') setl ww+=h endif " echomsg "________" " before we use let line=line(".") if in_imap && len(getline(".")) > col(".") let col = col(".")+1 else let col = col(".") endif " execute "normal l" let step = ( a:forward > 0 ? "l" : "h" ) let synstack = map(synstack(line, col), 'synIDattr( v:val, "name")') let synstackh = map(synstack(line, max([1, col-1])), 'synIDattr( v:val, "name")') let DelimiterCount = count(synstack, 'Delimiter') let ScriptCount = count(synstack, 'texSuperscript') + count(synstack, 'texSubscript') let ScriptsCount = count(synstack, 'texSuperscripts') + count(synstack, 'texSubscripts') let StatementCount = count(synstack, 'texStatement') let StatementCounth = count(synstackh, 'texStatement') && col(".") > 1 let SectionCount = count(synstack, 'texSection') let TypeStyleCount = count(synstack, 'texTypeStyle') let TypeStyleCounth = count(synstackh, 'texTypeStyle') && col(".") > 1 let MathTextCount = count(synstack, 'texMathText') let MathTextCounth = count(synstackh, 'texMathText') && col(".") > 1 let RefZoneCount = count(synstack, 'texRefZone') let RefZoneCounth = count(synstackh, 'texRefZone') && col(".") > 1 let RefOptionCount = count(synstack, 'texRefOption') let RefOptionCounth = count(synstackh, 'texRefOption') && !count(synstackh, 'Delimiter') && col(".") > 1 let CiteCount = count(synstack, 'texCite') let CiteCounth = count(synstackh, 'texCite') && !count(synstackh, 'Delimiter') && col(".") > 1 let MatcherCount = count(synstack, 'texMatcher') let MatcherCounth = count(synstackh, 'texMatcher') && !count(synstackh, 'Delimiter') && col(".") > 1 let MathMatcherCount = count(synstack, 'texMathMatcher') let MathMatcherCounth = count(synstackh, 'texMathMatcher') && !count(synstackh, 'Delimiter') && col(".") > 1 let SectionNameCount = count(synstack, 'texSectionName') let SectionNameCounth = count(synstackh, 'texSectionName') && !count(synstackh, 'Delimiter') && col(".") > 1 let SectionMarkerCount = count(synstack, 'texSectionMarker') let SectionModifierCount = count(synstack, 'texSectionModifier') let SectionModifierCounth = count(synstackh, 'texSectionModifier') && !count(synstackh, 'Delimiter') && col(".") > 1 " let MathZonesCount = len(filter(copy(synstack), 'v:val =~ ''^texMathZone[A-Z]''')) " let g:col = col(".") " let g:line = line(".") if DelimiterCount let syntax = [ 'Delimiter' ] elseif StatementCount && StatementCounth && step == "h" let syntax = [ 'texStatement' ] elseif StatementCount && step != "h" let syntax = [ 'texStatement' ] elseif SectionCount let syntax = [ 'texSection' ] elseif ScriptCount if a:how == 1 let syntax = [ 'texSuperscript', 'texSubscript'] else let syntax = [ 'texSuperscripts', 'texSubscripts'] endif elseif TypeStyleCount && TypeStyleCounth && step == "h" let syntax = [ 'texTypeStyle' ] elseif TypeStyleCount && step != "h" let syntax = [ 'texTypeStyle' ] elseif RefZoneCount && RefZoneCounth && step == "h" let syntax = [ 'texRefZone' ] elseif RefZoneCount && step != "h" let syntax = [ 'texRefZone' ] elseif RefOptionCount && RefOptionCounth && step == "h" let syntax = [ 'texRefOption' ] elseif RefOptionCount && step != "h" let syntax = [ 'texRefOption' ] elseif CiteCount && CiteCounth && step == "h" let syntax = [ 'texCite' ] elseif CiteCount && step != "h" let syntax = [ 'texCite' ] elseif MatcherCount && MatcherCounth && step == "h" let syntax = [ 'texMatcher' ] elseif MatcherCount && step != "h" let syntax = [ 'texMatcher' ] elseif MathMatcherCount && MathMatcherCounth && step == "h" let syntax = [ 'texMathMatcher' ] elseif MathMatcherCount && step != "h" let syntax = [ 'texMathMatcher' ] elseif SectionNameCount && SectionNameCounth && step == "h" let syntax = [ 'texSectionName' ] elseif SectionNameCount && step != "h" let syntax = [ 'texSectionName' ] elseif SectionMarkerCount let syntax = [ 'texSectionMarker' ] elseif SectionModifierCount && SectionModifierCounth && step == "h" let syntax = [ 'texSectionModifier' ] elseif SectionModifierCount && step != "h" let syntax = [ 'texSectionModifier' ] elseif MathTextCount && MathTextCounth && step == "h" let syntax = [ 'texMathText' ] elseif MathTextCount && step != "h" let syntax = [ 'texMathText' ] " elseif MathZonesCount " This might be slow " but we might change 'normal l' to 'normal w' " let syntax = [ 'texMathZoneA', 'texMathZoneB', 'texMathZoneC', 'texMathZoneD', 'texMathZoneE', 'texMathZoneF', 'texMathZoneG', 'texMathZoneH', 'texMathZoneI', 'texMathZoneJ', 'texMathZoneK', 'texMathZoneL', 'texMathZoneT', 'texMathZoneV', 'texMathZoneW', 'texMathZoneX', 'texMathZoneY' ] else " Go after first Delimiter let i=0 let DelimiterCount = count(synstack, 'Delimiter') while !DelimiterCount exe "normal " . step let synstack = map(synstack(line("."), col(".")), 'synIDattr( v:val, "name")') let DelimiterCount = count(synstack, 'Delimiter') if i == 1 let DelimiterCount = 0 endif let i+=1 endwhile if in_imap normal a endif return "Delimiter motion" endif let true = 0 for syn in syntax let true += count(synstack, syn) endfor let initial_count = true while true >= initial_count let true = 0 execute "normal " . step let synstack = map(synstack(line("."), col(".")), 'synIDattr( v:val, "name")') for syn in syntax let true += count(synstack, syn) endfor " echomsg string(synstack) . " " . string(syntax) . " " . true endwhile while getline(".")[col(".")] =~ '^{\|}\|(\|)\|\[\|\]$' exe "normal l" endwhile if getline(".")[col(".")-2] == "{" exe "normal h" endif let &l:whichwrap = join(whichwrap, ',') if in_imap normal a " else " normal l endif if step == "l" && syntax == [ 'Delimiter' ] normal h endif endfunction "}}} " ctrl-j motion " {{{ ctrl-j motion " New motion function! JMotion(flag) " Note: pattern to match only commands which do not have any arguments: " '\(\\\w\+\>\s*{\)\@!\\\w\+\>' if a:flag !~# 'b' let pattern = '\%(\]\zs\|{\zs\|}\zs\|(\zs\|)\zs\|\[\zs\|\]\zs\|\$\zs\|^\zs\s*$\|\(\\\w\+\>\s*{\)\@!\\\w\+\>\zs\)' else let pattern = '\%(\]\|{\|}\|(\|)\|\[\|\]\|\$\|^\s*$\|\(\\\w\+\>\s*{\)\@!\\\w\+\>\)' endif if getline(line(".")) =~ '&' let pattern = '\%(&\s*\zs\|^\s*\zs\)\|' . pattern endif " let g:col = col(".") " sometimes this doesn't work - in normal mode go to " end of line and press 'a' - then col(".") is not working! " let g:let = getline(line("."))[col(".")-1] " let g:con = getline(line("."))[col(".")-1] =~ '\%(\$\|{\|}\|(\|)\|\[\|\]\)' && col(".") < len(getline(line("."))) if getline(line("."))[col(".")-1] =~ '\%(\$\|{\|}\|(\|)\|\[\|\]\)' && a:flag !~# 'b' if col(".") == len(getline(line("."))) execute "normal a " else call cursor(line("."), col(".")+1) endif return else call search(pattern, a:flag) " In the imaps we use 'a' for the backward move and 'i' for forward move! let condition = getline(line("."))[col(".")-1] =~ '\%(\$\|{\|}\|(\|)\|\[\|\]\)' if a:flag !~# 'b' && col(".") == len(getline(line("."))) && condition " Add a space at the end of line and move there execute "normal a " endif endif endfunction "}}} endif "}}} " Add newly opened files to t:buflist. call s:buflist() " Commands And Maps: " {{{ command! -buffer SkipCommentForward :call SkipComment('fs', 'n') command! -buffer SkipCommentBackward :call SkipComment('bs', 'n') vmap SkipCommentForward :call SkipComment('fs', 'v') vmap SkipCommentBackward :call SkipComment('bs', 'v', col(".")) imap TexSyntaxMotionForward :call TexSyntaxMotion(1,1,1)a imap TexSyntaxMotionBackward :call TexSyntaxMotion(0,1,1)a nmap TexSyntaxMotionForward :call TexSyntaxMotion(1,1) nmap TexSyntaxMotionBackward :call TexSyntaxMotion(0,1) imap TexJMotionForward :call JMotion('')i imap TexJMotionBackward :call JMotion('b')a nmap TexJMotionForward :call JMotion('') nmap TexJMotionBackward :call JMotion('b') command! -buffer -nargs=1 -complete=buffer MakeToc :echo s:maketoc(fnamemodify(, ":p"))[fnamemodify(, ":p")] command! -buffer -bang -nargs=? TOC :call TOC() command! -buffer CTOC :call CTOC() command! -buffer -bang Labels :call Labels() command! -buffer -count=1 -nargs=? -complete=customlist,Env_compl NEnv :call GotoEnvironment('sW',) | let v:searchforward=1 command! -buffer -count=1 -nargs=? -complete=customlist,Env_compl PEnv :call GotoEnvironment('bsW',) | let v:searchforward=0 nnoremap GotoNextEnvironment :NEnv nnoremap GotoPreviousEnvironment :PEnv nnoremap GotoNextMath :NEnv math nnoremap GotoPreviousMath :PEnv math nnoremap GotoNextInlineMath :Nenv inlinemath nnoremap GotoPreviousInlineMath :PEnv inlinemath nnoremap GotoNextDisplayedMath :NEnv displayedmath nnoremap GotoPreviousDisplayedMath :PEnv displayedmath nnoremap GotoNextSubSection :call GotoSection("", "s", '"\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\s*{", ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', '') onoremap GotoNextSubSection :call GotoSection("", "s","\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\s*{", 'vim') vnoremap vGotoNextSubSection m':exe "normal! gv"exe "normal! w"call search('^\([^%]\|\\\@exe "normal! b" nnoremap GotoNextSection :call GotoSection("", "s", "\\\\\\%(section\\\\|chapter\\\\|part\\)\\s*{", ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', '') onoremap GotoNextSection :call GotoSection("", "s", "\\\\\\%(section\\\\|chapter\\\\|part\\)\\s*{", 'vim') vnoremap vGotoNextSection m':exe "normal! gv"exe "normal! w"call search('^\([^%]\|\\\@exe "normal! b" nnoremap GotoNextChapter :call GotoSection("", "s", "\\\\\\%(chapter\\\\|part\\)\\s*{", ( g:atp_mapNn ? 'atp' : 'vim' )) onoremap GotoNextChapter :call GotoSection("", "s", "\\\\\\%(chapter\\\\|part\\)\\s*{", 'vim') vnoremap vGotoNextChapter m':exe "normal! gv"exe "normal! w"call search('^\([^%]\|\\\@exe "normal! b" nnoremap GotoNextPart :call GotoSection("", "s", "\\\\part\\s*{", ( g:atp_mapNn ? 'atp' : 'vim' ), 'n') onoremap GotoNextPart :call GotoSection("", "s", "\\\\part\\s*{", 'vim', 'n') vnoremap vGotoNextPart m':exe "normal! gv"exe "normal! w"call search('^\([^%]\|\\\@exe "normal! b" command! -buffer -bang -count=1 -nargs=? -complete=customlist,Env_compl NSSSec :call GotoSection(, "s", '\\\%(subsubsection\|subsection\|section\|chapter\|part\)\s*{', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', ) command! -buffer -bang -count=1 -nargs=? -complete=customlist,Env_compl NSSec :call GotoSection(, "s", '\\\%(subsection\|section\|chapter\|part\)\s*{', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', ) command! -buffer -bang -count=1 -nargs=? -complete=customlist,Env_compl NSec :call GotoSection(, "s", '\\\%(section\|chapter\|part\)\s*{', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', ) command! -buffer -bang -count=1 -nargs=? -complete=customlist,Env_compl NChap :call GotoSection(, "s", '\\\%(chapter\|part\)\s*{', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', ) command! -buffer -bang -count=1 -nargs=? -complete=customlist,Env_compl NPart :call GotoSection(, "s", '\\part\s*{', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', ) nnoremap GotoPreviousSubSection :call GotoSection("", "sb", "\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\s*{", ( g:atp_mapNn ? 'atp' : 'vim' ), 'n') onoremap GotoPreviousSubSection :call GotoSection("", "sb", "\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\s*{", 'vim') vnoremap vGotoPreviousSubSection m':exe "normal! gv"call search('\\\%(subsection\\\\|section\\|chapter\\|part\)\s*{\\|\\begin\s*{\s*document\s*}', 'bW') nnoremap GotoPreviousSection :call GotoSection("", "sb", "\\\\\\%(section\\\\|chapter\\\\|part\\)\\s*{", ( g:atp_mapNn ? 'atp' : 'vim' ), 'n') onoremap GotoPreviousSection :call GotoSection("", "sb", "\\\\\\%(section\\\\|chapter\\\\|part\\)\\s*{", 'vim') vnoremap vGotoPreviousSection m':exe "normal! gv"call search('\\\%(section\\|chapter\\|part\)\s*{\\|\\begin\s*{\s*document\s*}', 'bW') nnoremap GotoPreviousChapter :call GotoSection("", "sb", "\\\\\\%(chapter\\\\|part\\)\\s*{", ( g:atp_mapNn ? 'atp' : 'vim' )) onoremap GotoPreviousChapter :call GotoSection("", "sb", "\\\\\\%(chapter\\\\|part\\)\\s*{", 'vim') vGotoPreviousChapter m':exe "normal! gv"call search('\\\%(chapter\\|part\)\s*{\\|\\begin\s*{\s*document\s*}', 'bW') nnoremap GotoPreviousPart :call GotoSection("", "sb", "\\\\part\\s*{", ( g:atp_mapNn ? 'atp' : 'vim' )) onoremap GotoPreviousPart :call GotoSection("", "sb", "\\\\part\\s*{", 'vim') vnoremap vGotoPreviousPart m':exe "normal! gv"call search('\\\%(part\)\s*{', 'bW') command! -buffer -bang -count=1 -nargs=? -complete=customlist,Env_compl PSSSec :call PreviousSection('\\\%(subsubsection\|subsection\|section\|chapter\|part\)', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', ) command! -buffer -bang -count=1 -nargs=? -complete=customlist,Env_compl PSSec :call GotoSection(, 'sb', '\\\%(subsection\|section\|chapter\|part\)', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', ) command! -buffer -bang -count=1 -nargs=? -complete=customlist,Env_compl PSec :call GotoSection(, 'sb', '\\\%(section\|chapter\|part\)', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', ) command! -buffer -bang -count=1 -nargs=? -complete=customlist,Env_compl PChap :call GotoSection(, 'sb', '\\\%(chapter\|part\)', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', ) command! -buffer -bang -count=1 -nargs=? -complete=customlist,Env_compl PPart :call GotoSection(, 'sb', '\\part\s*{', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', ) command! -buffer NInput :call Input("w") | let v:searchforward = 1 command! -buffer PInput :call Input("bw") | let v:searchforward = 0 command! -buffer -nargs=? -bang -complete=customlist,GotoFileComplete GotoFile :call GotoFile(,, 0) command! -buffer -nargs=? -bang -complete=customlist,GotoFileComplete EditInputFile :call GotoFile(,, 0) " }}} " vimeif data[0]['text'] =~ 'No Unique Match Found' echohl WarningMsg " echomsg "No Unique Match Found" echohl None returnfdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1 command! -bang -nargs=? -complete=customlist,GotoLabelCompletion GotoLabel :call GotoLabel(, ) ftplugin/ATP_files/options.vim [[[1 1921 " Author: Marcin Szamotulski " Description: This file contains all the options defined on startup of ATP " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " Language: tex " Last Change: " NOTE: you can add your local settings to ~/.atprc.vim or " ftplugin/ATP_files/atprc.vim file " Some options (functions) should be set once: let s:did_options = exists("s:did_options") ? 1 : 0 let g:atp_reload = 0 "{{{ tab-local variables " We need to know bufnumber and bufname in a tabpage. " ToDo: we can set them with s: and call them using stack " (how to make the stack invisible to the user! let t:atp_bufname = bufname("") let t:atp_bufnr = bufnr("") let t:atp_winnr = winnr() " autocommands for buf/win numbers " These autocommands are used to remember the last opened buffer number and its " window number: if !s:did_options augroup ATP_TabLocalVariables au! au BufLeave *.tex let t:atp_bufname = resolve(fnamemodify(bufname(""),":p")) au BufLeave *.tex let t:atp_bufnr = bufnr("") " t:atp_winnr the last window used by tex, ToC or Labels buffers: au WinEnter *.tex let t:atp_winnr = winnr("#") au WinEnter __ToC__ let t:atp_winnr = winnr("#") au WinEnter __Labels__ let t:atp_winnr = winnr("#") au TabEnter *.tex let t:atp_SectionStack = ( exists("t:atp_SectionStack") ? t:atp_SectionStack : [] ) augroup END endif "}}} " ATP Debug Variables: (to debug atp behaviour) " {{{ debug variables if !exists("g:atp_debugML") " debug MakeLatex (compiler.vim) let g:atp_debugML = 0 endif if !exists("g:atp_debugGAF") " debug aptlib#GrepAuxFile let g:atp_debugGAF = 0 endif if !exists("g:atp_debugSCP") " debug s:SelectCurrentParapgrahp (LatexBox_motion.vim) let g:atp_debugSCP = 0 endif if !exists("g:atp_debugSIT") " debug SearchInTree (search.vim) let g:atp_debugSIT = 0 endif if !exists("g:atp_debugSync") " debug forward search (vim->viewer) (search.vim) let g:atp_debugSync = 0 endif if !exists("g:atp_debugV") " debug ViewOutput() (compiler.vim) let g:atp_debugV = 0 endif if !exists("g:atp_debugLPS") " Debug s:LoadProjectFile() (history.vim) " (currently it gives just the loading time info) let g:atp_debugLPS = 0 endif if !exists("g:atp_debugCompiler") " Debug s:Compiler() function (compiler.vim) " when equal 2 output is more verbose. let g:atp_debugCompiler = 0 endif if !exists("g:atp_debugST") " Debug CallBack() function (compiler.vim) let g:atp_debugCallBack = 0 endif if !exists("g:atp_debugST") " Debug SyncTex() (various.vim) function let g:atp_debugST = 0 endif if !exists("g:atp_debugCLE") " Debug atplib#CloseLastEnvironment() let g:atp_debugCLE = 0 endif if !exists("g:atp_debugMainScript") " loading times of scripts sources by main script file: ftpluing/tex_atp.vim " NOTE: it is listed here for completeness, it can only be set in " ftplugin/tex_atp.vim script file. let g:atp_debugMainScript = 0 endif if !exists("g:atp_debugProject") " LoadScript(), LoadProjectScript(), WriteProject() " The value that is set in history file matters! let g:atp_debugProject = 0 endif if !exists("g:atp_debugCB") " atplib#CheckBracket() let g:atp_debugCB = 0 endif if !exists("g:atp_debugCLB") " atplib#CloseLastBracket() let g:atp_debugCLB = 0 endif if !exists("g:atp_debugTC") " atplib#TabCompletion() let g:atp_debugTC = 0 endif if !exists("g:atp_debugBS") " atplib#searchbib() " atplib#showresults() " BibSearch() in ATP_files/search.vim " log file: /tmp/ATP_log let g:atp_debugBS = 0 endif if !exists("g:atp_debugToF") " TreeOfFiles() ATP_files/common.vim let g:atp_debugToF = 0 endif if !exists("g:atp_debgTOF") " TreeOfFiles() redirect only the output to " /tmp/ATP_log let g:atp_debugTOF = 0 endif if !exists("g:atp_debugBabel") " echo msg if babel language is not supported. let g:atp_debugBabel = 0 endif "}}} " vim options + indentation " {{{ Vim options " {{{ Intendation if !exists("g:atp_indentation") let g:atp_indentation=1 endif " if !exists("g:atp_tex_indent_paragraphs") " let g:atp_tex_indent_paragraphs=1 " endif if g:atp_indentation " setl indentexpr=GetTeXIndent() " setl nolisp " setl nosmartindent " setl autoindent " setl indentkeys+=},=\\item,=\\bibitem,=\\[,=\\],= " let prefix = expand(':p:h:h') " exe 'so '.prefix.'/indent/tex_atp.vim' let prefix = expand(':p:h') exe 'so '.prefix.'/LatexBox_indent.vim' endif " }}} setl nrformats=alpha setl keywordprg=texdoc\ -m " Borrowed from tex.vim written by Benji Fisher: " Set 'comments' to format dashed lists in comments setlocal com=sO:%\ -,mO:%\ \ ,eO:%%,:% " Set 'commentstring' to recognize the % comment character: " (Thanks to Ajit Thakkar.) setlocal cms=%%s " Allow "[d" to be used to find a macro definition: " Recognize plain TeX \def as well as LaTeX \newcommand and \renewcommand . " I may as well add the AMS-LaTeX DeclareMathOperator as well. let &l:define='\\\([egx]\|char\|mathchar\|count\|dimen\|muskip\|skip\|toks\)\=' \ . 'def\|\\font\|\\\(future\)\=let' \ . '\|\\new\(count\|dimen\|skip\|muskip\|box\|toks\|read\|write' \ . '\|fam\|insert\)' \ . '\|\\\(re\)\=new\(boolean\|command\|counter\|environment\|font' \ . '\|if\|length\|savebox\|theorem\(style\)\=\)\s*\*\=\s*{\=' \ . '\|DeclareMathOperator\s*{\=\s*' \ . '\|DeclareFixedFont\s*{\s*' let g:filetype = &l:filetype if &l:filetype != "plaintex" setlocal include=\\\\input\\(\\s*{\\)\\=\\\\|\\\\include\\s*{ else setlocal include=\\\\input endif setlocal suffixesadd=.tex setlocal includeexpr=substitute(v:fname,'\\%(.tex\\)\\?$','.tex','') " TODO set define and work on the above settings, these settings work with [i " command but not with [d, [D and [+CTRL D (jump to first macro definition) " This was throwing all autocommand groups to the command line on startup. " Anyway this is not very good. " augroup ATP_makeprg " au VimEnter *.tex let &l:makeprg="vim --servername " . v:servername . " --remote-expr 'Make()'" " augroup " }}} " Buffer Local Variables: " {{{ buffer variables let b:atp_running = 0 " these are all buffer related variables: let s:optionsDict= { \ "atp_TexOptions" : "-synctex=1", \ "atp_ReloadOnError" : "1", \ "atp_OpenViewer" : "1", \ "atp_autex" : !&l:diff && expand("%:e") == 'tex', \ "atp_ProjectScript" : "1", \ "atp_Viewer" : has("win26") || has("win32") || has("win64") || has("win95") || has("win32unix") ? "AcroRd32.exe" : "okular" , \ "atp_TexFlavor" : &l:filetype, \ "atp_XpdfServer" : fnamemodify(b:atp_MainFile,":t:r"), \ "atp_OutDir" : substitute(fnameescape(fnamemodify(resolve(expand("%:p")),":h")) . "/", '\\\s', ' ' , 'g'), \ "atp_TmpDir" : substitute(b:atp_OutDir . "/.tmp", '\/\/', '\/', 'g'), \ "atp_TexCompiler" : &filetype == "plaintex" ? "pdftex" : "pdflatex", \ "atp_TexCompilerVariable" : "max_print_line=2000", \ "atp_auruns" : "1", \ "atp_TruncateStatusSection" : "40", \ "atp_LastBibPattern" : "" } let g:optionsDict=deepcopy(s:optionsDict) " the above atp_OutDir is not used! the function s:SetOutDir() is used, it is just to " remember what is the default used by s:SetOutDir(). " This function sets options (values of buffer related variables) which were " not already set by the user. " {{{ s:SetOptions let s:ask = { "ask" : "0" } function! s:SetOptions() let s:optionsKeys = keys(s:optionsDict) let s:optionsinuseDict = getbufvar(bufname("%"),"") "for each key in s:optionsKeys set the corresponding variable to its default "value unless it was already set in .vimrc file. for key in s:optionsKeys if string(get(s:optionsinuseDict,key, "optionnotset")) == string("optionnotset") && key != "atp_OutDir" && key != "atp_autex" || key == "atp_TexCompiler" call setbufvar(bufname("%"), key, s:optionsDict[key]) elseif key == "atp_OutDir" " set b:atp_OutDir and the value of errorfile option if !exists("b:atp_OutDir") call s:SetOutDir(1) endif let s:ask["ask"] = 1 endif endfor " Do not run tex on tex files which are in texmf tree " Exception: if it is opened using the command ':EditInputFile' " which sets this itself. if string(get(s:optionsinuseDict,"atp_autex", 'optionnotset')) == string('optionnotset') let atp_texinputs=split(substitute(substitute(system("kpsewhich -show-path tex"),'\/\/\+','\/','g'),'!\|\n','','g'),':') call remove(atp_texinputs, index(atp_texinputs, '.')) call filter(atp_texinputs, 'b:atp_OutDir =~# v:val') let b:atp_autex = ( len(atp_texinputs) ? 0 : s:optionsDict['atp_autex']) endif if !exists("b:TreeOfFiles") || !exists("b:ListOfFiles") || !exists("b:TypeDict") || !exists("b:LevelDict") if exists("b:atp_MainFile") let atp_MainFile = atplib#FullPath(b:atp_MainFile) call TreeOfFiles(atp_MainFile) else echomsg "b:atp_MainFile " . "doesn't exists." endif endif endfunction "}}} call s:SetOptions() "}}} " Global Variables: (almost all) " {{{ global variables if !exists("g:atp_cpcmd") || g:atp_reload " This will avoid using -i switch which might be defined in an alias file. " This doesn't make much harm, but it might be better. let g:atp_cpcmd="/bin/cp" endif " Variables for imaps, standard environment names: if !exists("g:atp_EnvNameTheorem") || g:atp_reload let g:atp_EnvNameTheorem="theorem" endif if !exists("g:atp_EnvNameDefinition") || g:atp_reload let g:atp_EnvNameDefinition="definition" endif if !exists("g:atp_EnvNameProposition") || g:atp_reload let g:atp_EnvNameProposition="proposition" endif if !exists("g:atp_EnvNameObservation") || g:atp_reload " This mapping is defined only in old layout: " i.e. if g:atp_env_maps_old == 1 let g:atp_EnvNameObservation="observation" endif if !exists("g:atp_EnvNameLemma") || g:atp_reload let g:atp_EnvNameLemma="lemma" endif if !exists("g:atp_EnvNameNote") || g:atp_reload let g:atp_EnvNameNote="note" endif if !exists("g:atp_EnvNameCorollary") || g:atp_reload let g:atp_EnvNameCorollary="corollary" endif if !exists("g:atp_EnvNameRemark") || g:atp_reload let g:atp_EnvNameRemark="remark" endif if !exists("g:atp_StarEnvDefault") || g:atp_reload " Values are "" or "*". " It will be added to enrionemnt names which support it. let g:atp_StarEnvDefault="" endif if !exists("g:atp_StarMathEnvDefault") || g:atp_reload " Values are "" or "*". " It will be added to enrionemnt names which support it. let g:atp_StarMathEnvDefault="" endif if !exists("g:atp_EnvOptions_enumerate") || g:atp_reload " add options to \begin{enumerate} for example [topsep=0pt,noitemsep] Then the " enumerate map E will put \begin{enumerate}[topsep=0pt,noitemsep] Useful " options of enumitem to make enumerate more condenced. let g:atp_EnvOptions_enumerate="" endif if !exists("g:atp_EnvOptions_itemize") || g:atp_reload " Similar to g:atp_enumerate_options. let g:atp_EnvOptions_itemize="" endif if !exists("g:atp_VimCompatible") || g:atp_reload " Used by: % (s:JumpToMatch in LatexBox_motion.vim). let g:atp_VimCompatible = "no" " It can be 0/1 or yes/no. endif if !exists("g:atp_CupsOptions") || g:atp_reload " lpr command options for completion of SshPrint command. let g:atp_CupsOptions = [ 'landscape=', 'scaling=', 'media=', 'sides=', 'Collate=', 'orientation-requested=', \ 'job-sheets=', 'job-hold-until=', 'page-ragnes=', 'page-set=', 'number-up=', 'page-border=', \ 'number-up-layout=', 'fitplot=', 'outputorder=', 'mirror=', 'raw=', 'cpi=', 'columns=', \ 'page-left=', 'page-right=', 'page-top=', 'page-bottom=', 'prettyprint=', 'nowrap=', 'position=', \ 'natural-scaling=', 'hue=', 'ppi=', 'saturation=', 'blackplot=', 'penwidth='] endif if !exists("g:atp_lprcommand") || g:atp_reload " Used by :SshPrint let g:atp_lprcommand = "lpr" endif if !exists("g:atp_iabbrev_leader") || g:atp_reload " Used for abbreviations: =theorem= (from both sides). let g:atp_iabbrev_leader = "=" endif if !exists("g:atp_bibrefRegister") || g:atp_reload " A register to which bibref obtained from AMS will be copied. let g:atp_bibrefRegister = "0" endif if !exists("g:atpbib_pathseparator") || g:atp_reload if has("win16") || has("win32") || has("win64") || has("win95") let g:atpbib_pathseparator = "\\" else let g:atpbib_pathseparator = "/" endif endif if !exists("g:atpbib_WgetOutputFile") || g:atp_reload let g:atpbib_WgetOutputFile = "amsref.html" endif if !exists("g:atpbib_wget") || g:atp_reload let g:atpbib_wget="wget" endif if !exists("g:atp_vmap_text_font_leader") || g:atp_reload let g:atp_vmap_text_font_leader="" endif if !exists("g:atp_vmap_environment_leader") || g:atp_reload let g:atp_vmap_environment_leader="" endif if !exists("g:atp_vmap_bracket_leader") || g:atp_reload let g:atp_vmap_bracket_leader="" endif if !exists("g:atp_vmap_big_bracket_leader") || g:atp_reload let g:atp_vmap_big_bracket_leader='b' endif if !exists("g:atp_map_forward_motion_leader") || g:atp_reload let g:atp_map_forward_motion_leader='>' endif if !exists("g:atp_map_backward_motion_leader") || g:atp_reload let g:atp_map_backward_motion_leader='<' endif if !exists("g:atp_RelativePath") || g:atp_reload " This is here only for completness, the default value is set in project.vim let g:atp_RelativePath = 1 endif if !exists("g:atp_SyncXpdfLog") || g:atp_reload let g:atp_SyncXpdfLog = 0 endif if !exists("g:atp_LogSync") || g:atp_reload let g:atp_LogSync = 0 endif function! s:Sync(...) let arg = ( a:0 >=1 ? a:1 : "" ) if arg == "on" let g:atp_LogSync = 1 elseif arg == "off" let g:atp_LogSync = 0 else let g:atp_LogSync = !g:atp_LogSync endif echomsg "g:atp_LogSync = " . g:atp_LogSync endfunction command! -buffer -nargs=? -complete=customlist,s:SyncComp LogSync :call s:Sync() function! s:SyncComp(ArgLead, CmdLine, CursorPos) return filter(['on', 'off'], "v:val =~ a:ArgLead") endfunction if !exists("g:atp_Compare") || g:atp_reload " Use b:changedtick variable to run s:Compiler automatically. let g:atp_Compare = "changedtick" endif if !exists("g:atp_babel") || g:atp_reload let g:atp_babel = 0 endif " if !exists("g:atp_closebracket_checkenv") || g:atp_reload " This is a list of environment names. They will be checked by " atplib#CloseLastBracket() function (if they are opened/closed: " ( \begin{array} ... will then close first \begin{array} and then ')' try let g:atp_closebracket_checkenv = [ 'array' ] " Changing this variable is not yet supported *see ToDo: in " atplib#CloseLastBracket() (autoload/atplib.vim) lockvar g:atp_closebracket_checkenv catch /E741:/ " echomsg "Changing this variable is not supported" endtry " endif " if !exists("g:atp_ProjectScript") || g:atp_reload " let g:atp_ProjectScript = 1 " endif if !exists("g:atp_OpenTypeDict") || g:atp_reload let g:atp_OpenTypeDict = { \ "pdf" : "xpdf", "ps" : "evince", \ "djvu" : "djview", "txt" : "split" , \ "tex" : "edit", "dvi" : "xdvi -s 5" } " for txt type files supported viewers: cat, gvim = vim = tabe, split, edit endif if !exists("g:atp_LibraryPath") || g:atp_reload let g:atp_LibraryPath = 0 endif if !exists("g:atp_statusOutDir") || g:atp_reload let g:atp_statusOutDir = 1 endif if !exists("g:atp_developer") || g:atp_reload let g:atp_developer = 0 endif if !exists("g:atp_mapNn") || g:atp_reload let g:atp_mapNn = 0 " This value is used only on startup, then :LoadHistory sets the default value. endif " user cannot change the value set by :LoadHistory on startup in atprc file. " " Unless using: " au VimEnter *.tex let b:atp_mapNn = 0 " " Recently I changed this: in project files it is " better to start with atp_mapNn = 0 and let the " user change it. if !exists("g:atp_TeXdocDefault") || g:atp_reload let g:atp_TeXdocDefault = '-a -I lshort' endif "ToDo: to doc. "ToDo: luatex! (can produce both!) if !exists("g:atp_CompilersDict") || g:atp_reload let g:atp_CompilersDict = { \ "pdflatex" : ".pdf", "pdftex" : ".pdf", \ "xetex" : ".pdf", "latex" : ".dvi", \ "tex" : ".dvi", "elatex" : ".dvi", \ "etex" : ".dvi", "luatex" : ".pdf"} endif if !exists("g:CompilerMsg_Dict") || g:atp_reload let g:CompilerMsg_Dict = { \ 'tex' : 'TeX', \ 'etex' : 'eTeX', \ 'pdftex' : 'pdfTeX', \ 'latex' : 'LaTeX', \ 'elatex' : 'eLaTeX', \ 'pdflatex' : 'pdfLaTeX', \ 'context' : 'ConTeXt', \ 'luatex' : 'LuaTeX', \ 'xetex' : 'XeTeX'} endif if !exists("g:ViewerMsg_Dict") || g:atp_reload let g:ViewerMsg_Dict = { \ 'xpdf' : 'Xpdf', \ 'xdvi' : 'Xdvi', \ 'kpdf' : 'Kpdf', \ 'okular' : 'Okular', \ 'evince' : 'Evince', \ 'acroread' : 'AcroRead', \ 'epdfview' : 'epdfView' } endif "ToDo: to doc. if !exists("g:atp_insert_updatetime") || g:atp_reload let g:atp_insert_updatetime = max([ 2000, &l:updatetime]) endif if !exists("g:atp_DefaultDebugMode") || g:atp_reload " recognised values: silent, debug. let g:atp_DefaultDebugMode = "silent" endif if !exists("g:atp_show_all_lines") || g:atp_reload " boolean let g:atp_show_all_lines = 0 endif if !exists("g:atp_ignore_unmatched") || g:atp_reload " boolean let g:atp_ignore_unmatched = 1 endif if !exists("g:atp_imap_first_leader") || g:atp_reload let g:atp_imap_first_leader = "#" endif if !exists("g:atp_imap_second_leader") || g:atp_reload let g:atp_imap_second_leader= "##" endif if !exists("g:atp_imap_third_leader") || g:atp_reload let g:atp_imap_third_leader = "]" endif if !exists("g:atp_imap_fourth_leader") || g:atp_reload let g:atp_imap_fourth_leader= "[" endif " todo: to doc. if !exists("g:atp_completion_font_encodings") || g:atp_reload let g:atp_completion_font_encodings = ['T1', 'T2', 'T3', 'T5', 'OT1', 'OT2', 'OT4', 'UT1'] endif " todo: to doc. if !exists("g:atp_font_encoding") || g:atp_reload let s:line=atplib#SearchPackage('fontenc') if s:line != 0 " the last enconding is the default one for fontenc, this we will " use let s:enc=matchstr(getline(s:line),'\\usepackage\s*\[\%([^,]*,\)*\zs[^]]*\ze\]\s*{fontenc}') else let s:enc='OT1' endif let g:atp_font_encoding=s:enc unlet s:line unlet s:enc endif if !exists("g:atp_no_star_environments") let g:atp_no_star_environments=['document', 'flushright', 'flushleft', 'center', \ 'enumerate', 'itemize', 'tikzpicture', 'scope', \ 'picture', 'array', 'proof', 'tabular', 'table' ] endif if !exists("g:atp_sizes_of_brackets") || g:atp_reload let g:atp_sizes_of_brackets={'\left': '\right', \ '\bigl' : '\bigr', \ '\Bigl' : '\Bigr', \ '\biggl' : '\biggr' , \ '\Biggl' : '\Biggr', \ '\big' : '\big', \ '\Big' : '\Big', \ '\bigg' : '\bigg', \ '\Bigg' : '\Bigg', \ '\' : '\', \ } " the last one is not a size of a bracket is to a hack to close \(:\), \[:\] and " \{:\} endif if !exists("g:atp_algorithmic_dict") || g:atp_reload let g:atp_algorithmic_dict = { 'IF' : 'ENDIF', 'FOR' : 'ENDFOR', 'WHILE' : 'ENDWHILE' } endif if !exists("g:atp_bracket_dict") || g:atp_reload let g:atp_bracket_dict = { '(' : ')', '{' : '}', '[' : ']', '\lceil' : '\rceil', '\lfloor' : '\rfloor', '\langle' : '\rangle', '\lgroup' : '\rgroup' } endif if !exists("g:atp_LatexBox") || g:atp_reload let g:atp_LatexBox = 1 endif if !exists("g:atp_check_if_LatexBox") || g:atp_reload let g:atp_check_if_LatexBox = 1 endif if !exists("g:atp_autex_check_if_closed") || g:atp_reload let g:atp_autex_check_if_closed = 1 endif if ( !exists("g:rmcommand") || g:atp_reload ) && executable("perltrash") let g:rmcommand="perltrash" elseif !exists("g:rmcommand") || g:atp_reload let g:rmcommand = "rm" endif if !exists("g:atp_env_maps_old") || g:atp_reload let g:atp_env_maps_old = 0 endif if !exists("g:atp_amsmath") || g:atp_reload let g:atp_amsmath=atplib#SearchPackage('ams') endif if !exists("g:atp_no_math_command_completion") || g:atp_reload let g:atp_no_math_command_completion = 0 endif if !exists("g:atp_tex_extensions") || g:atp_reload let g:atp_tex_extensions = ["tex.project.vim", "aux", "log", "bbl", "blg", "spl", "snm", "nav", "thm", "brf", "out", "toc", "mpx", "idx", "ind", "ilg", "maf", "glo", "mtc[0-9]", "mtc1[0-9]", "pdfsync", "synctex.gz" ] endif if !exists("g:atp_delete_output") || g:atp_reload let g:atp_delete_output = 0 endif if !exists("g:keep") || g:atp_reload let g:keep=[ "log", "aux", "toc", "bbl", "ind", "pdfsync", "synctex.gz" ] endif if !exists("g:atp_ssh") || g:atp_reload let g:atp_ssh=substitute(system("whoami"),'\n','','') . "@localhost" endif " opens bibsearch results in vertically split window. if !exists("g:vertical") || g:atp_reload let g:vertical = 1 endif if !exists("g:matchpair") || g:atp_reload let g:matchpair="(:),[:],{:}" endif if !exists("g:texmf") || g:atp_reload let g:texmf = $HOME . "/texmf" endif if !exists("g:atp_compare_embedded_comments") || g:atp_reload || g:atp_compare_embedded_comments != 1 let g:atp_compare_embedded_comments = 0 endif if !exists("g:atp_compare_double_empty_lines") || g:atp_reload || g:atp_compare_double_empty_lines != 0 let g:atp_compare_double_empty_lines = 1 endif "TODO: put toc_window_with and labels_window_width into DOC file if !exists("t:toc_window_width") || g:atp_reload if exists("g:toc_window_width") let t:toc_window_width = g:toc_window_width else let t:toc_window_width = 30 endif endif if !exists("t:atp_labels_window_width") || g:atp_reload if exists("g:labels_window_width") let t:atp_labels_window_width = g:labels_window_width else let t:atp_labels_window_width = 30 endif endif if !exists("g:atp_completion_limits") || g:atp_reload let g:atp_completion_limits = [40,60,80,120] endif if !exists("g:atp_long_environments") || g:atp_reload let g:atp_long_environments = [] endif if !exists("g:atp_no_complete") || g:atp_reload let g:atp_no_complete = ['document'] endif " if !exists("g:atp_close_after_last_closed") || g:atp_reload " let g:atp_close_after_last_closed=1 " endif if !exists("g:atp_no_env_maps") || g:atp_reload let g:atp_no_env_maps = 0 endif if !exists("g:atp_extra_env_maps") || g:atp_reload let g:atp_extra_env_maps = 0 endif " todo: to doc. Now they go first. " if !exists("g:atp_math_commands_first") || g:atp_reload " let g:atp_math_commands_first=1 " endif if !exists("g:atp_completion_truncate") || g:atp_reload let g:atp_completion_truncate = 4 endif " ToDo: to doc. " add server call back (then automatically reads errorfiles) if !exists("g:atp_statusNotif") || g:atp_reload if has('clientserver') && !empty(v:servername) let g:atp_statusNotif = 1 else let g:atp_statusNotif = 0 endif endif if !exists("g:atp_statusNotifHi") || g:atp_reload let g:atp_statusNotifHi = 0 endif if !exists("g:atp_callback") || g:atp_reload if exists("g:atp_status_notification") && g:atp_status_notification == 1 let g:atp_callback = 1 elseif has('clientserver') && !empty(v:servername) let g:atp_callback = 1 else let g:atp_callback = 0 endif endif " ToDo: to doc. " I switched this off. " if !exists("g:atp_complete_math_env_first") || g:atp_reload " let g:atp_complete_math_env_first=0 " endif " }}} " Project Settings: " {{{1 if !exists("g:atp_ProjectLocalVariables") || g:atp_reload " This is a list of variable names which will be preserved in project files let g:atp_ProjectLocalVariables = [ \ "b:atp_MainFile", "g:atp_mapNn", "b:atp_autex", \ "b:atp_TexCompiler", "b:atp_TexFlavor", "b:atp_OutDir" , \ "b:atp_auruns", "b:atp_ReloadOnErr", "b:atp_OpenViewer", \ "b:atp_XpdfServer", "b:atp_ProjectDir", "b:atp_Viewer" \ ] endif " the variable a:1 is the name of the variable which stores the list of variables to " save. function! SaveProjectVariables(...) let variables_List = ( a:0 >= 1 ? {a:1} : g:atp_ProjectLocalVariables ) let variables_Dict = {} for var in variables_List if exists(var) call extend(variables_Dict, { var : {var} }) endif endfor return variables_Dict endfunction function! RestoreProjectVariables(variables_Dict) for var in keys(a:variables_Dict) let g:cmd = "let " . var . "=" . string(a:variables_Dict[var]) " echo g:cmd exe "let " . var . "=" . string(a:variables_Dict[var]) endfor endfunction " }}}1 " This is to be extended into a nice function which shows the important options " and allows to reconfigure atp "{{{ ShowOptions let s:file = expand(':p') function! s:ShowOptions(bang,...) let pattern = a:0 >= 1 ? a:1 : ".*," let mlen = max(map(copy(keys(s:optionsDict)), "len(v:val)")) echo "Local buffer variables:" redraw for key in keys(s:optionsDict) let space = "" for s in range(mlen-len(key)+1) let space .= " " endfor if "b:".key =~ pattern " if patn != '' && "b:".key !~ patn echo "b:".key.space.getbufvar(bufnr(""), key) " endif endif endfor if a:bang == "!" " Show some global options echo "\n" echo "Global variables (defined in ".s:file."):" let saved_loclist = getloclist(0) execute "lvimgrep /^\\s*let\\s\\+g:/j " . fnameescape(s:file) let global_vars = getloclist(0) call setloclist(0, saved_loclist) let var_list = [] for var in global_vars let var_name = matchstr(var['text'], '^\s*let\s\+\zsg:\S*\ze\s*=') if len(var_name) call add(var_list, var_name) endif endfor " Filter only matching variables that exists! call filter(var_list, 'count(var_list, v:val) == 1 && exists(v:val)') let mlen = max(map(copy(var_list), "len(v:val)")) for var_name in var_list let space = "" for s in range(mlen-len(var_name)+1) let space .= " " endfor if var_name =~ pattern && var_name !~ '_command\|_amsfonts\|ams_negations\|tikz_\|keywords' " if patn != '' && var_name !~ patn echo var_name.space.string({var_name}) " endif endif endfor endif endfunction command! -buffer -bang -nargs=* ShowOptions :call ShowOptions(, ) "}}} " Debug Mode Variables: " {{{ Debug Mode let t:atp_DebugMode = g:atp_DefaultDebugMode " there are three possible values of t:atp_DebugMode " silent/normal/debug let t:atp_QuickFixOpen = 0 if !s:did_options augroup ATP_DebugMode au FileType *.tex let t:atp_DebugMode = g:atp_DefaultDebugMode " When opening the quickfix error buffer: au FileType qf let t:atp_QuickFixOpen=1 " When closing the quickfix error buffer (:close, :q) also end the Debug Mode. au FileType qf au BufUnload let t:atp_DebugMode = g:atp_DefaultDebugMode | let t:atp_QuickFixOpen = 0 au FileType qf setl nospell augroup END endif "}}} " Babel " {{{1 variables if !exists("g:atp_keymaps") || g:atp_reload let g:atp_keymaps = { \ 'british' : 'ignore', 'english' : 'ignore', \ 'USenglish' : 'ignore', 'UKenglish' : 'ignore', \ 'american' : 'ignore', \ 'bulgarian' : 'bulgarian-bds', 'croatian' : 'croatian', \ 'czech' : 'czech', 'greek' : 'greek', \ 'plutonikogreek': 'greek', 'hebrew' : 'hebrew', \ 'russian' : 'russian-jcuken', 'serbian' : 'serbian', \ 'slovak' : 'slovak', 'ukrainian' : 'ukrainian-jcuken', \ 'polish' : 'polish-slash' } else "extend the existing dictionary with default values not ovverriding what is defind: for lang in [ 'croatian', 'czech', 'greek', 'hebrew', 'serbian', 'slovak' ] call extend(g:atp_keymaps, { lang : lang }, 'keep') endfor call extend(g:atp_keymaps, { 'british' : 'ignore' }, 'keep') call extend(g:atp_keymaps, { 'american' : 'ignore' }, 'keep') call extend(g:atp_keymaps, { 'english' : 'ignore' }, 'keep') call extend(g:atp_keymaps, { 'UKenglish' : 'ignore' }, 'keep') call extend(g:atp_keymaps, { 'USenglish' : 'ignore' }, 'keep') call extend(g:atp_keymaps, { 'bulgarian' : 'bulgarian-bds' }, 'keep') call extend(g:atp_keymaps, { 'plutonikogreek' : 'greek' }, 'keep') call extend(g:atp_keymaps, { 'russian' : 'russian-jcuken' }, 'keep') call extend(g:atp_keymaps, { 'ukrainian' : 'ukrainian-jcuken' }, 'keep') endif " {{{1 function function! Babel() " Todo: make notification. if &filetype != "tex" || !exists("b:atp_MainFile") || !has("keymap") " This only works for LaTeX documents. " but it might work for plain tex documents as well! return endif let atp_MainFile = atplib#FullPath(b:atp_MainFile) let saved_loclist = getloclist(0) try execute '1lvimgrep /^[^%]*\\usepackage.*{babel}/j ' . fnameescape(atp_MainFile) " Find \usepackage[babel_options]{babel} - this is the only way that one can " pass options to babel. catch /E480:/ return catch /E683:/ return endtry let babel_line = get(get(getloclist(0), 0, {}), 'text', '') call setloclist(0, saved_loclist) let languages = split(matchstr(babel_line, '\[\zs[^]]*\ze\]'), ',') if len(languages) == 0 return endif let default_language = get(languages, '-1', '') if g:atp_debugBabel echomsg "Babel : defualt language:" . default_language endif let keymap = get(g:atp_keymaps, default_language, '') if keymap == '' if g:atp_debugBabel echoerr "No keymap in g:atp_keymaps.\n" . babel_line endif return endif if keymap != 'ignore' execute "set keymap=" . keymap else execute "set keymap=" endif endfunction command! -buffer Babel :call Babel() " {{{1 start up if g:atp_babel call Babel() endif " }}}1 " These are two functions which sets options for Xpdf and Xdvi. " {{{ Xpdf, Xdvi " xdvi - supports forward and reverse searching " {{{ SetXdvi function! SetXdvi() " Remove menu entries let Compiler = get(g:CompilerMsg_Dict, matchstr(b:atp_TexCompiler, '^\s*\S*'), 'Compiler') let Viewer = get(g:ViewerMsg_Dict, matchstr(b:atp_Viewer, '^\s*\S*'), 'View\ Output') try execute "aunmenu LaTeX.".Compiler execute "aunmenu LaTeX.".Compiler."\\ debug" execute "aunmenu LaTeX.".Compiler."\\ twice" execute "aunmenu LaTeX.View\\ with\\ ".Viewer catch /E329:/ endtry " Set new options: let b:atp_TexCompiler = "latex " let b:atp_TexOptions = " -src-specials " let b:atp_Viewer="xdvi " . " -editor '" . v:progname . " --servername " . v:servername . " --remote-wait +%l %f'" map rs :call RevSearch() try nmenu 550.65 &LaTeX.Reverse\ Search:map\ rs :RevSearch catch /E329:/ endtry " Put new menu entries: let Compiler = get(g:CompilerMsg_Dict, matchstr(b:atp_TexCompiler, '^\s*\zs\S*'), 'Compile') let Viewer = get(g:ViewerMsg_Dict, matchstr(b:atp_Viewer, '^\s*\zs\S*'), "View\\ Output") execute "nmenu 550.5 &LaTeX.&".Compiler.":TEX :TEX" execute "nmenu 550.6 &LaTeX.".Compiler."\\ debug:TEX\\ debug :DTEX" execute "nmenu 550.7 &LaTeX.".Compiler."\\ &twice:2TEX :2TEX" execute "nmenu 550.10 LaTeX.&View\\ with\\ ".Viewer.":ViewOutput :ViewOutput" endfunction command! -buffer SetXdvi :call SetXdvi() nnoremap SetXdvi :call SetXdvi() " }}} " xpdf - supports server option (we use the reoding mechanism, which allows to " copy the output file but not reload the viewer if there were errors during " compilation (b:atp_ReloadOnError variable) " {{{ SetXpdf function! SetPdf(viewer) " Remove menu entries. let Compiler = get(g:CompilerMsg_Dict, matchstr(b:atp_TexCompiler, '^\s*\S*'), 'Compiler') let Viewer = get(g:ViewerMsg_Dict, matchstr(b:atp_Viewer, '^\s*\S*'), 'View\ Output') try execute "aunmenu LaTeX.".Compiler execute "aunmenu LaTeX.".Compiler."\\ debug" execute "aunmenu LaTeX.".Compiler."\\ twice" execute "aunmenu LaTeX.View\\ with\\ ".Viewer catch /E329:/ endtry let b:atp_TexCompiler = "pdflatex" " We have to clear tex options (for example -src-specials set by :SetXdvi) let b:atp_TexOptions = "-synctex=1" let b:atp_Viewer = a:viewer " Delete menu entry. try silent aunmenu LaTeX.Reverse\ Search catch /E329:/ endtry " Put new menu entries: let Compiler = get(g:CompilerMsg_Dict, matchstr(b:atp_TexCompiler, '^\s*\zs\S*'), 'Compile') let Viewer = get(g:ViewerMsg_Dict, matchstr(b:atp_Viewer, '^\s*\zs\S*'), 'View\ Output') execute "nmenu 550.5 &LaTeX.&".Compiler. ":TEX :TEX" execute "nmenu 550.6 &LaTeX." .Compiler. "\\ debug:TEX\\ debug :DTEX" execute "nmenu 550.7 &LaTeX." .Compiler. "\\ &twice:2TEX :2TEX" execute "nmenu 550.10 LaTeX.&View\\ with\\ ".Viewer. ":ViewOutput :ViewOutput" endfunction command! -buffer SetXpdf :call SetPdf('xpdf') command! -buffer SetOkular :call SetPdf('okular') nnoremap SetXpdf :call SetPdf('xpdf') nnoremap SetOkular :call SetPdf('okular') " }}} "" " }}} " These are functions which toggles some of the options: "{{{ Toggle Functions if !s:did_options " {{{ ATP_ToggleAuTeX " command! -buffer -count=1 TEX :call TEX() function! ATP_ToggleAuTeX(...) let on = ( a:0 >=1 ? ( a:1 == 'on' ? 1 : 0 ) : !b:atp_autex ) if on let b:atp_autex=1 echo "automatic tex processing is ON" silent! aunmenu LaTeX.Toggle\ AuTeX\ [off] silent! aunmenu LaTeX.Toggle\ AuTeX\ [on] menu 550.75 &LaTeX.&Toggle\ AuTeX\ [on]b:atp_autex :ToggleAuTeX cmenu 550.75 &LaTeX.&Toggle\ AuTeX\ [on]b:atp_autex ToggleAuTeX imenu 550.75 &LaTeX.&Toggle\ AuTeX\ [on]b:atp_autex :ToggleAuTeXa else let b:atp_autex=0 silent! aunmenu LaTeX.Toggle\ AuTeX\ [off] silent! aunmenu LaTeX.Toggle\ AuTeX\ [on] menu 550.75 &LaTeX.&Toggle\ AuTeX\ [off]b:atp_autex :ToggleAuTeX cmenu 550.75 &LaTeX.&Toggle\ AuTeX\ [off]b:atp_autex ToggleAuTeX imenu 550.75 &LaTeX.&Toggle\ AuTeX\ [off]b:atp_autex :ToggleAuTeXa echo "automatic tex processing is OFF" endif endfunction "}}} " {{{ ATP_ToggleSpace " Special Space for Searching let s:special_space="[off]" function! ATP_ToggleSpace(...) let on = ( a:0 >=1 ? ( a:1 == 'on' ? 1 : 0 ) : maparg('','c') == "" ) if on echomsg "special space is on" cmap \_s\+ let s:special_space="[on]" silent! aunmenu LaTeX.Toggle\ Space\ [off] silent! aunmenu LaTeX.Toggle\ Space\ [on] menu 550.78 &LaTeX.&Toggle\ Space\ [on]cmap\ \ \\_s\\+ :ToggleSpace cmenu 550.78 &LaTeX.&Toggle\ Space\ [on]cmap\ \ \\_s\\+ ToggleSpace imenu 550.78 &LaTeX.&Toggle\ Space\ [on]cmap\ \ \\_s\\+ :ToggleSpacea tmenu &LaTeX.&Toggle\ Space\ [on] cmap \_s\+ is curently on else echomsg "special space is off" cunmap let s:special_space="[off]" silent! aunmenu LaTeX.Toggle\ Space\ [on] silent! aunmenu LaTeX.Toggle\ Space\ [off] menu 550.78 &LaTeX.&Toggle\ Space\ [off]cmap\ \ \\_s\\+ :ToggleSpace cmenu 550.78 &LaTeX.&Toggle\ Space\ [off]cmap\ \ \\_s\\+ ToggleSpace imenu 550.78 &LaTeX.&Toggle\ Space\ [off]cmap\ \ \\_s\\+ :ToggleSpacea tmenu &LaTeX.&Toggle\ Space\ [off] cmap \_s\+ is curently off endif endfunction "}}} " {{{ ATP_ToggleCheckMathOpened " This function toggles if ATP is checking if editing a math mode. " This is used by insert completion. " ToDo: to doc. function! ATP_ToggleCheckMathOpened(...) let on = ( a:0 >=1 ? ( a:1 == 'on' ? 1 : 0 ) : !g:atp_MathOpened ) " if g:atp_MathOpened if !on let g:atp_MathOpened = 0 echomsg "check if in math environment is off" silent! aunmenu LaTeX.Toggle\ Check\ if\ in\ Math\ [on] silent! aunmenu LaTeX.Toggle\ Check\ if\ in\ Math\ [off] menu 550.79 &LaTeX.Toggle\ &Check\ if\ in\ Math\ [off]g:atp_MathOpened \ :ToggleCheckMathOpened cmenu 550.79 &LaTeX.Toggle\ &Check\ if\ in\ Math\ [off]g:atp_MathOpened \ ToggleCheckMathOpened imenu 550.79 &LaTeX.Toggle\ &Check\ if\ in\ Math\ [off]g:atp_MathOpened \ :ToggleCheckMathOpeneda else let g:atp_MathOpened = 1 echomsg "check if in math environment is on" silent! aunmenu LaTeX.Toggle\ Check\ if\ in\ Math\ [off] silent! aunmenu LaTeX.Toggle\ Check\ if\ in\ Math\ [off] menu 550.79 &LaTeX.Toggle\ &Check\ if\ in\ Math\ [on]g:atp_MathOpened \ :ToggleCheckMathOpened cmenu 550.79 &LaTeX.Toggle\ &Check\ if\ in\ Math\ [on]g:atp_MathOpened \ ToggleCheckMathOpened imenu 550.79 &LaTeX.Toggle\ &Check\ if\ in\ Math\ [on]g:atp_MathOpened \ :ToggleCheckMathOpeneda endif endfunction "}}} " {{{ ATP_ToggleCallBack function! ATP_ToggleCallBack(...) let on = ( a:0 >=1 ? ( a:1 == 'on' ? 1 : 0 ) : !g:atp_callback ) if !on let g:atp_callback = 0 echomsg "call back is off" silent! aunmenu LaTeX.Toggle\ Call\ Back\ [on] silent! aunmenu LaTeX.Toggle\ Call\ Back\ [off] menu 550.80 &LaTeX.Toggle\ &Call\ Back\ [off]g:atp_callback \ :call ToggleCallBack() cmenu 550.80 &LaTeX.Toggle\ &Call\ Back\ [off]g:atp_callback \ call ToggleCallBack() imenu 550.80 &LaTeX.Toggle\ &Call\ Back\ [off]g:atp_callback \ :call ToggleCallBack()a else let g:atp_callback = 1 echomsg "call back is on" silent! aunmenu LaTeX.Toggle\ Call\ Back\ [on] silent! aunmenu LaTeX.Toggle\ Call\ Back\ [off] menu 550.80 &LaTeX.Toggle\ &Call\ Back\ [on]g:atp_callback \ :call ToggleCallBack() cmenu 550.80 &LaTeX.Toggle\ &Call\ Back\ [on]g:atp_callback \ call ToggleCallBack() imenu 550.80 &LaTeX.Toggle\ &Call\ Back\ [on]g:atp_callback \ :call ToggleCallBack()a endif endfunction "}}} " {{{ ATP_ToggleDebugMode " ToDo: to doc. " TODO: it would be nice to have this command (and the map) in quickflist (FileType qf) " describe DEBUG MODE in doc properly. function! ATP_ToggleDebugMode(...) let on = ( a:0 >=1 ? ( a:1 == 'on' ? 1 : 0 ) : t:atp_DebugMode != "debug" ) if !on echomsg "debug mode is off" silent! aunmenu 550.20.5 &LaTeX.&Log.Toggle\ &Debug\ Mode\ [on] silent! aunmenu 550.20.5 &LaTeX.&Log.Toggle\ &Debug\ Mode\ [off] menu 550.20.5 &LaTeX.&Log.Toggle\ &Debug\ Mode\ [off]t:atp_DebugMode \ :ToggleDebugMode cmenu 550.20.5 &LaTeX.&Log.Toggle\ &Debug\ Mode\ [off]t:atp_DebugMode \ ToggleDebugMode imenu 550.20.5 &LaTeX.&Log.Toggle\ &Debug\ Mode\ [off]t:atp_DebugMode \ :ToggleDebugModea silent! aunmenu LaTeX.Toggle\ Call\ Back\ [on] silent! aunmenu LaTeX.Toggle\ Call\ Back\ [off] menu 550.80 &LaTeX.Toggle\ &Call\ Back\ [off]g:atp_callback \ :ToggleDebugMode cmenu 550.80 &LaTeX.Toggle\ &Call\ Back\ [off]g:atp_callback \ ToggleDebugMode imenu 550.80 &LaTeX.Toggle\ &Call\ Back\ [off]g:atp_callback \ :ToggleDebugModea let t:atp_DebugMode = g:atp_DefaultDebugMode silent cclose else echomsg "debug mode is on" silent! aunmenu 550.20.5 LaTeX.Log.Toggle\ Debug\ Mode\ [off] silent! aunmenu 550.20.5 &LaTeX.&Log.Toggle\ &Debug\ Mode\ [on] menu 550.20.5 &LaTeX.&Log.Toggle\ &Debug\ Mode\ [on]t:atp_DebugMode \ :ToggleDebugMode cmenu 550.20.5 &LaTeX.&Log.Toggle\ &Debug\ Mode\ [on]t:atp_DebugMode \ ToggleDebugMode imenu 550.20.5 &LaTeX.&Log.Toggle\ &Debug\ Mode\ [on]t:atp_DebugMode \ :ToggleDebugModea silent! aunmenu LaTeX.Toggle\ Call\ Back\ [on] silent! aunmenu LaTeX.Toggle\ Call\ Back\ [off] menu 550.80 &LaTeX.Toggle\ &Call\ Back\ [on]g:atp_callback \ :ToggleDebugMode cmenu 550.80 &LaTeX.Toggle\ &Call\ Back\ [on]g:atp_callback \ ToggleDebugMode imenu 550.80 &LaTeX.Toggle\ &Call\ Back\ [on]g:atp_callback \ :ToggleDebugModea let g:atp_callback=1 let t:atp_DebugMode = "debug" let winnr = bufwinnr("%") silent copen exe winnr . " wincmd w" endif endfunction augroup ATP_DebugModeCommandsAndMaps au! au FileType qf command! -buffer ToggleDebugMode :call ToggleDebugMode() au FileType qf nnoremap D :ToggleDebugMode augroup END " }}} " {{{ ATP_ToggleTab " switches on/off the map for TabCompletion function! ATP_ToggleTab(...) if mapcheck('','i') !~ 'atplib#TabCompletion' let on = ( a:0 >=1 ? ( a:1 == 'on' ? 1 : 0 ) : mapcheck('','i') !~# 'atplib#TabCompletion' ) if !on iunmap echo ' map turned off' else imap =atplib#TabCompletion(1) echo ' map turned on' endif endif endfunction " }}} endif " Commands And Maps: command! -buffer -nargs=? -complete=customlist,atplib#OnOffComp ToggleAuTeX :call ATP_ToggleAuTeX() nnoremap ToggleAuTeX :call ATP_ToggleAuTeX() command! -buffer -nargs=? -complete=customlist,atplib#OnOffComp ToggleSpace :call ATP_ToggleSpace() nnoremap ToggleSpace :call ATP_ToggleSpace() command! -buffer -nargs=? -complete=customlist,atplib#OnOffComp ToggleCheckMathOpened :call ATP_ToggleCheckMathOpened() nnoremap ToggleCheckMathOpened :call ATP_ToggleCheckMathOpened() command! -buffer -nargs=? -complete=customlist,atplib#OnOffComp ToggleCallBack :call ATP_ToggleCallBack() nnoremap ToggleCallBack :call ATP_ToggleCallBack() command! -buffer -nargs=? -complete=customlist,atplib#OnOffComp ToggleDebugMode :call ATP_ToggleDebugMode() nnoremap ToggleDebugMode :call ATP_ToggleDebugMode() command! -buffer -nargs=? -complete=customlist,atplib#OnOffComp ToggleTab :call ATP_ToggleTab() nnoremap ToggleTab :call ATP_ToggleTab() inoremap ToggleTab :call ATP_ToggleTab() "}}} " Tab Completion Variables: " {{{ TAB COMPLETION variables " ( functions are in autoload/atplib.vim ) " try let g:atp_completion_modes=[ \ 'commands', 'labels', \ 'tikz libraries', 'environment names', \ 'close environments' , 'brackets', \ 'input files', 'bibstyles', \ 'bibitems', 'bibfiles', \ 'documentclass', 'tikzpicture commands', \ 'tikzpicture', 'tikzpicture keywords', \ 'package names', 'font encoding', \ 'font family', 'font series', \ 'font shape', 'algorithmic', \ 'beamerthemes', 'beamerinnerthemes', \ 'beamerouterthemes', 'beamercolorthemes', \ 'beamerfontthemes', 'todonotes' ] lockvar 2 g:atp_completion_modes catch /E741:/ endtry if !exists("g:atp_completion_modes_normal_mode") || g:atp_reload let g:atp_completion_modes_normal_mode=[ \ 'close environments' , 'brackets', 'algorithmic' ] lockvar g:atp_completion_modes_normal_mode endif " By defualt all completion modes are ative. if !exists("g:atp_completion_active_modes") || g:atp_reload let g:atp_completion_active_modes=deepcopy(g:atp_completion_modes) endif if !exists("g:atp_completion_active_modes_normal_mode") || g:atp_reload let g:atp_completion_active_modes_normal_mode=deepcopy(g:atp_completion_modes_normal_mode) endif if !exists("g:atp_sort_completion_list") || g:atp_reload let g:atp_sort_completion_list = 12 endif " Note: to remove completions: 'inline_math' or 'displayed_math' one has to " remove also: 'close_environments' /the function atplib#CloseLastEnvironment can " close math instead of an environment/. " ToDo: make list of complition commands from the input files. " ToDo: make complition fot \cite, and for \ref and \eqref commands. " ToDo: there is second such a list! line 3150 let g:atp_Environments=['array', 'abstract', 'center', 'corollary', \ 'definition', 'document', 'description', 'displaymath', \ 'enumerate', 'example', 'eqnarray', \ 'flushright', 'flushleft', 'figure', 'frontmatter', \ 'keywords', \ 'itemize', 'lemma', 'list', 'letter', 'notation', 'minipage', \ 'proof', 'proposition', 'picture', 'theorem', 'tikzpicture', \ 'tabular', 'table', 'tabbing', 'thebibliography', 'titlepage', \ 'quotation', 'quote', \ 'remark', 'verbatim', 'verse' ] let g:atp_amsmath_environments=['align', 'alignat', 'equation', 'gather', \ 'multline', 'split', 'substack', 'flalign', 'smallmatrix', 'subeqations', \ 'pmatrix', 'bmatrix', 'Bmatrix', 'vmatrix' ] " if short name is no_short_name or '' then both means to do not put " anything, also if there is no key it will not get a short name. let g:atp_shortname_dict = { 'theorem' : 'thm', \ 'proposition' : 'prop', 'definition' : 'defi', \ 'lemma' : 'lem', 'array' : 'ar', \ 'abstract' : 'no_short_name', \ 'tikzpicture' : 'tikz', 'tabular' : 'table', \ 'table' : 'table', 'proof' : 'pr', \ 'corollary' : 'cor', 'enumerate' : 'enum', \ 'example' : 'ex', 'itemize' : 'it', \ 'item' : 'itm', 'algorithmic' : 'alg', \ 'algorithm' : 'alg', \ 'remark' : 'rem', 'notation' : 'not', \ 'center' : '', 'flushright' : '', \ 'flushleft' : '', 'quotation' : 'quot', \ 'quot' : 'quot', 'tabbing' : '', \ 'picture' : 'pic', 'minipage' : '', \ 'list' : 'list', 'figure' : 'fig', \ 'verbatim' : 'verb', 'verse' : 'verse', \ 'thebibliography' : '', 'document' : 'no_short_name', \ 'titlepave' : '', 'align' : 'eq', \ 'alignat' : 'eq', 'equation' : 'eq', \ 'gather' : 'eq', 'multline' : 'eq', \ 'split' : 'eq', 'substack' : '', \ 'flalign' : 'eq', 'displaymath' : 'eq', \ 'part' : 'prt', 'chapter' : 'chap', \ 'section' : 'sec', 'subsection' : 'ssec', \ 'subsubsection' : 'sssec', 'paragraph' : 'par', \ 'subparagraph' : 'spar', 'subequations' : 'eq' } " ToDo: Doc. " Usage: \label{l:shorn_env_name . g:atp_separator if !exists("g:atp_separator") || g:atp_reload let g:atp_separator=':' endif if !exists("g:atp_no_separator") || g:atp_reload let g:atp_no_separator = 0 endif if !exists("g:atp_no_short_names") || g:atp_reload let g:atp_env_short_names = 1 endif " the separator will not be put after the environments in this list: " the empty string is on purpose: to not put separator when there is " no name. let g:atp_no_separator_list=['', 'titlepage'] " let g:atp_package_list=sort(['amsmath', 'amssymb', 'amsthm', 'amstex', " \ 'babel', 'booktabs', 'bookman', 'color', 'colorx', 'chancery', 'charter', 'courier', " \ 'enumerate', 'euro', 'fancyhdr', 'fancyheadings', 'fontinst', " \ 'geometry', 'graphicx', 'graphics', " \ 'hyperref', 'helvet', 'layout', 'longtable', " \ 'newcent', 'nicefrac', 'ntheorem', 'palatino', 'stmaryrd', 'showkeys', 'tikz', " \ 'qpalatin', 'qbookman', 'qcourier', 'qswiss', 'qtimes', 'verbatim', 'wasysym']) " the command \label is added at the end. let g:atp_Commands=["\\begin{", "\\end{", \ "\\cite", "\\nocite{", "\\ref{", "\\pageref{", "\\eqref{", "\\item", \ "\\emph{", "\\documentclass{", "\\usepackage{", \ "\\section", "\\subsection", "\\subsubsection", "\\part", \ "\\chapter", "\\appendix", "\\subparagraph", "\\paragraph", \ "\\textbf{", "\\textsf{", "\\textrm{", "\\textit{", "\\texttt{", \ "\\textsc{", "\\textsl{", "\\textup{", "\\textnormal", "\\textcolor{", \ "\\bfseries", "\\mdseries", "\\bigskip", "\\bibitem", \ "\\tiny", "\\scriptsize", "\\footnotesize", "\\small", \ "\\noindent", "\\normalfont", "\normalsize", "\\normalsize", "\\normal", \ "\\hfill", "\\hspace","\\hline", \ "\\large", "\\Large", "\\LARGE", "\\huge", "\\HUGE", \ "\\overline", \ "\\usefont{", "\\fontsize{", "\\selectfont", "\\fontencoding{", "\\fontfamiliy{", "\\fontseries{", "\\fontshape{", \ "\\rmdefault", "\\sfdefault", "\\ttdefault", "\\bfdefault", "\\mddefault", "\\itdefault", \ "\\sldefault", "\\scdefault", "\\updefault", "\\renewcommand{", "\\newcommand{", \ "\\addcontentsline{", "\\addtocontents", \ "\\input", "\\include", "\\includeonly", "\\includegraphics", \ "\\savebox", "\\sbox", "\\usebox", "\\rule", "\\raisebox{", \ "\\parbox{", "\\mbox{", "\\makebox{", "\\framebox{", "\\fbox{", \ "\\medskip", "\\smallskip", "\\vskip", "\\vfil", "\\vfill", "\\vspace{", \ "\\hrulefill", "\hfil", "\\dotfill", \ "\\thispagestyle{", "\\mathnormal", "\\markright{", "\\markleft{", "\\pagestyle{", "\\pagenumbering{", \ "\\author{", "\\date{", "\\thanks{", "\\title{", \ "\\maketitle", \ "\\marginpar", "\\indent", "\\par", "\\sloppy", "\\pagebreak", "\\nopagebreak", \ "\\newpage", "\\newline", "\\newtheorem{", "\\linebreak", "\\line", "\\linespread{", \ "\\hyphenation{", "\\fussy", "\\eject", \ "\\enlagrethispage{", "\\clearpage", "\\cleardoublepage", \ "\\caption{", \ "\\opening{", "\\name{", "\\makelabels{", "\\location{", "\\closing{", "\\address{", \ "\\signature{", "\\stopbreaks", "\\startbreaks", \ "\\newcounter{", "\\refstepcounter{", \ "\\roman{", "\\Roman{", "\\stepcounter{", "\\setcounter{", \ "\\usecounter{", "\\value{", \ "\\newlength{", "\\setlength{", "\\addtolength{", "\\settodepth{", \ "\\settoheight{", "\\settowidth{", "\\stretch{", \ "\\width", "\\height", "\\depth", "\\totalheight", \ "\\footnote{", "\\footnotemark", "\\footnotetetext", \ "\\bibliography{", "\\bibliographystyle{", "\\baselineskip", \ "\\flushbottom", "\\onecolumn", "\\raggedbottom", "\\twocolumn", \ "\\alph{", "\\Alph{", "\\arabic{", "\\fnsymbol{", "\\reversemarginpar", \ "\\exhyphenpenalty", \ "\\topmargin", "\\oddsidemargin", "\\evensidemargin", "\\headheight", "\\headsep", \ "\\textwidth", "\\textheight", "\\marginparwidth", "\\marginparsep", "\\marginparpush", "\\footskip", "\\hoffset", \ "\\voffset", "\\paperwidth", "\\paperheight", "\\theequation", "\\thepage", "\\usetikzlibrary{", \ "\\tableofcontents", "\\newfont{", "\\phantom", \ "\\DeclareRobustCommand", "\\DeclareFixedFont", "\\DeclareMathSymbol", \ "\\DeclareTextFontCommand", "\\DeclareMathVersion", "\\DeclareSymbolFontAlphabet", \ "\\DeclareMathDelimiter", "\\DeclareMathAccent", "\\DeclareMathRadical", \ "\\SetMathAlphabet", "\\show", "\\CheckCommand", "\\mathnormal", \ "\\pounds", "\\magstep{", "\\hyperlink", "\\newenvironment{", \ "\\renewenvironemt{", "\\DeclareFixedFont", "\\layout", "\\parskip" ] let g:atp_picture_commands=[ "\\put", "\\circle", "\\dashbox", "\\frame{", \"\\framebox(", "\\line(", "\\linethickness{", \ "\\makebox(", "\\\multiput(", "\\oval(", "\\put", \ "\\shortstack", "\\vector(" ] " ToDo: end writting layout commands. " ToDo: MAKE COMMANDS FOR PREAMBULE. let g:atp_math_commands=["\\forall", "\\exists", "\\emptyset", "\\aleph", "\\partial", \ "\\nabla", "\\Box", "\\bot", "\\top", "\\flat", "\\natural", \ "\\mathbf{", "\\mathsf{", "\\mathrm{", "\\mathit{", "\\mathtt{", "\\mathcal{", \ "\\mathop{", "\\mathversion", "\\limits", "\\text{", "\\leqslant", "\\leq", "\\geqslant", "\\geq", \ "\\gtrsim", "\\lesssim", "\\gtrless", "\\left", "\\right", \ "\\rightarrow", "\\Rightarrow", "\\leftarrow", "\\Leftarrow", "\\iff", \ "\\oplus", "\\otimes", "\\odot", "\\oint", \ "\\leftrightarrow", "\\Leftrightarrow", "\\downarrow", "\\Downarrow", \ "\\overline", "\\underline", "\\overbrace{", "\\Uparrow", \ "\\Longrightarrow", "\\longrightarrow", "\\Longleftarrow", "\\longleftarrow", \ "\\overrightarrow{", "\\overleftarrow{", "\\underrightarrow{", "\\underleftarrow{", \ "\\uparrow", "\\nearrow", "\\searrow", "\\swarrow", "\\nwarrow", "\\mapsto", "\\longmapsto", \ "\\hookrightarrow", "\\hookleftarrow", "\\gets", "\\to", "\\backslash", \ "\\sum", "\\bigsum", "\\cup", "\\bigcup", "\\cap", "\\bigcap", \ "\\prod", "\\coprod", "\\bigvee", "\\bigwedge", "\\wedge", \ "\\int", "\\bigoplus", "\\bigotimes", "\\bigodot", "\\times", \ "\\smile", "\\frown", \ "\\dashv", "\\vdash", "\\vDash", "\\Vdash", "\\models", "\\sim", "\\simeq", \ "\\prec", "\\preceq", "\\preccurlyeq", "\\precapprox", "\\mid", \ "\\succ", "\\succeq", "\\succcurlyeq", "\\succapprox", "\\approx", \ "\\ldots", "\\cdots", "\\vdots", "\\ddots", "\\circ", \ "\\thickapprox", "\\cong", "\\bullet", \ "\\lhd", "\\unlhd", "\\rhd", "\\unrhd", "\\dagger", "\\ddager", "\\dag", "\\ddag", \ "\\vartriangleright", "\\vartriangleleft", \ "\\triangle", "\\triangledown", "\\trianglerighteq", "\\trianglelefteq", \ "\\copyright", "\\textregistered", "\\puonds", \ "\\big", "\\Big", "\\Bigg", "\\huge", \ "\\bigr", "\\Bigr", "\\biggr", "\\Biggr", \ "\\bigl", "\\Bigl", "\\biggl", "\\Biggl", \ "\\hat", "\\grave", "\\bar", "\\acute", "\\mathring", "\\check", \ "\\dots", "\\dot", "\\vec", "\\breve", \ "\\tilde", "\\widetilde" , "\\widehat", "\\ddot", \ "\\sqrt", "\\frac", "\\binom{", "\\cline", "\\vline", "\\hline", "\\multicolumn{", \ "\\nouppercase", "\\sqsubseteq", "\\sqsubset", "\\sqsupseteq", "\\sqsupset", \ "\\square", "\\blacksquare", \ "\\nexists", "\\varnothing", "\\Bbbk", "\\circledS", \ "\\complement", "\\hslash", "\\hbar", \ "\\eth", "\\rightrightarrows", "\\leftleftarrows", "\\rightleftarrows", "\\leftrighrarrows", \ "\\downdownarrows", "\\upuparrows", "\\rightarrowtail", "\\leftarrowtail", \ "\\rightharpoondown", "\\rightharpoonup", "\\rightleftharpoons", "\\leftharpoondown", "\\leftharpoonup", \ "\\twoheadrightarrow", "\\twoheadleftarrow", "\\rceil", "\\lceil", "\\rfloor", "\\lfloor", \ "\\bigtriangledown", "\\bigtriangleup", "\\ominus", "\\bigcirc", "\\amalg", "\\asymp", \ "\\vert", "\\Arrowvert", "\\arrowvert", "\\bracevert", "\\lmoustache", "\\rmoustache", \ "\\setminus", "\\sqcup", "\\sqcap", "\\bowtie", "\\owns", "\\oslash", \ "\\lnot", "\\notin", "\\neq", "\\smile", "\\frown", "\\equiv", "\\perp", \ "\\quad", "\\qquad", "\\stackrel", "\\displaystyle", "\\textstyle", "\\scriptstyle", "\\scriptscriptstyle", \ "\\langle", "\\rangle", "\\Diamond", "\\lgroup", "\\rgroup", "\\propto", "\\Join", "\\div", \ "\\land", "\\star", "\\uplus", "\\leadsto", "\\rbrack", "\\lbrack", "\\mho", \ "\\diamondsuit", "\\heartsuit", "\\clubsuit", "\\spadesuit", "\\top", "\\ell", \ "\\imath", "\\jmath", "\\wp", "\\Im", "\\Re", "\\prime", "\\ll", "\\gg" ] let g:atp_math_commands_PRE=[ "\\diagdown", "\\diagup", "\\subset", "\\subseteq", "\\supset", "\\supsetneq", \ "\\sharp", "\\underline", "\\underbrace{", ] " commands defined by the user in input files. " ToDo: to doc. " ToDo: this doesn't work with input files well enough. " Returns a list of two lists: [ commanad_names, enironment_names ] " The BufEnter augroup doesn't work with EditInputFile, but at least it works " when entering. Debuging shows that when entering new buffer it uses " wrong b:atp_MainFile, it is still equal to the bufername and not the " real main file. Maybe it is better to use s:mainfile variable. if !exists("g:atp_local_completion") || g:atp_reload let g:atp_local_completion = 1 endif let g:atp_math_commands_non_expert_mode=[ "\\leqq", "\\geqq", "\\succeqq", "\\preceqq", \ "\\subseteqq", "\\supseteqq", "\\gtrapprox", "\\lessapprox" ] " requiers amssymb package: let g:atp_ams_negations=[ "\\nless", "\\ngtr", "\\lneq", "\\gneq", "\\nleq", "\\ngeq", "\\nleqslant", "\\ngeqslant", \ "\\nsim", "\\nconq", "\\nvdash", "\\nvDash", \ "\\nsubseteq", "\\nsupseteq", \ "\\varsubsetneq", "\\subsetneq", "\\varsupsetneq", "\\supsetneq", \ "\\ntriangleright", "\\ntriangleleft", "\\ntrianglerighteq", "\\ntrianglelefteq", \ "\\nrightarrow", "\\nleftarrow", "\\nRightarrow", "\\nLeftarrow", \ "\\nleftrightarrow", "\\nLeftrightarrow", "\\nsucc", "\\nprec", "\\npreceq", "\\nsucceq", \ "\\precneq", "\\succneq", "\\precnapprox", "\\ltimes", "\\rtimes" ] let g:atp_ams_negations_non_expert_mode=[ "\\lneqq", "\\ngeqq", "\\nleqq", "\\ngeqq", "\\nsubseteqq", \ "\\nsupseteqq", "\\subsetneqq", "\\supsetneqq", "\\nsucceqq", "\\precneqq", "\\succneqq" ] " ToDo: add more amsmath commands. let g:atp_amsmath_commands=[ "\\boxed", "\\intertext", "\\multiligngap", "\\shoveleft{", "\\shoveright{", "\\notag", "\\tag", \ "\\notag", "\\raistag{", "\\displaybreak", "\\allowdisplaybreaks", "\\numberwithin{", \ "\\hdotsfor{" , "\\mspace{", \ "\\negthinspace", "\\negmedspace", "\\negthickspace", "\\thinspace", "\\medspace", "\\thickspace", \ "\\leftroot{", "\\uproot{", "\\overset{", "\\underset{", "\\substack{", "\\sideset{", \ "\\dfrac", "\\tfrac", "\\cfrac", "\\dbinom{", "\\tbinom{", "\\smash", \ "\\lvert", "\\rvert", "\\lVert", "\\rVert", "\\DeclareMatchOperator{", \ "\\arccos", "\\arcsin", "\\arg", "\\cos", "\\cosh", "\\cot", "\\coth", "\\csc", "\\deg", "\\det", \ "\\dim", "\\exp", "\\gcd", "\\hom", "\\inf", "\\injlim", "\\ker", "\\lg", "\\lim", "\\liminf", "\\limsup", \ "\\log", "\\min", "\\max", "\\Pr", "\\projlim", "\\sec", "\\sin", "\\sinh", "\\sup", "\\tan", "\\tanh", \ "\\varlimsup", "\\varliminf", "\\varinjlim", "\\varprojlim", "\\mod", "\\bmod", "\\pmod", "\\pod", "\\sideset", \ "\\iint", "\\iiint", "\\iiiint", "\\idotsint", "\\tag", \ "\\varGamma", "\\varDelta", "\\varTheta", "\\varLambda", "\\varXi", "\\varPi", "\\varSigma", \ "\\varUpsilon", "\\varPhi", "\\varPsi", "\\varOmega" ] " ToDo: integrate in TabCompletion (amsfonts, euscript packages). let g:atp_amsfonts=[ "\\mathbb{", "\\mathfrak{", "\\mathscr{" ] " not yet supported: in TabCompletion: let g:atp_amsextra_commands=[ "\\sphat", "\\sptilde" ] let g:atp_fancyhdr_commands=["\\lfoot{", "\\rfoot{", "\\rhead{", "\\lhead{", \ "\\cfoot{", "\\chead{", "\\fancyhead{", "\\fancyfoot{", \ "\\fancypagestyle{", "\\fancyhf{}", "\\headrulewidth", "\\footrulewidth", \ "\\rightmark", "\\leftmark", "\\markboth{", \ "\\chaptermark", "\\sectionmark", "\\subsectionmark", \ "\\fancyheadoffset", "\\fancyfootoffset", "\\fancyhfoffset"] let g:atp_makeidx_commands=[ "\\makeindex", "\\index{", "\\printindex" ] " ToDo: remove tikzpicture from above and integrate the " tikz_envirnoments variable " \begin{pgfonlayer}{background} (complete the second argument as " well} " " Tikz command cuold be accitve only in tikzpicture and after \tikz " command! There is a way to do that. " let g:atp_tikz_environments=['tikzpicture', 'scope', 'pgfonlayer', 'background' ] " ToDo: this should be completed as packages. let g:atp_tikz_libraries=sort(['arrows', 'automata', 'backgrounds', 'calc', 'calendar', 'chains', 'decorations', \ 'decorations.footprints', 'decorations.fractals', \ 'decorations.markings', 'decorations.pathmorphing', \ 'decorations.replacing', 'decorations.shapes', \ 'decorations.text', 'er', 'fadings', 'fit', \ 'folding', 'matrix', 'mindmap', 'scopes', \ 'patterns', 'pteri', 'plothandlers', 'plotmarks', \ 'plcaments', 'pgflibrarypatterns', 'pgflibraryshapes', \ 'pgflibraryplotmarks', 'positioning', 'replacements', \ 'shadows', 'shapes.arrows', 'shapes.callout', 'shapes.geometric', \ 'shapes.gates.logic.IEC', 'shapes.gates.logic.US', 'shapes.misc', \ 'shapes.multipart', 'shapes.symbols', 'topaths', 'through', 'trees' ]) " tikz keywords = begin without '\'! " ToDo: add mote keywords: done until page 145. " ToDo: put them in a correct order!!! " ToDo: completion for arguments in brackets [] for tikz commands. let g:atp_tikz_commands=[ "\\begin", "\\end", "\\matrix", "\\node", "\\shadedraw", \ "\\draw", "\\tikz", "\\tikzset", \ "\\path", "\\filldraw", "\\fill", "\\clip", "\\drawclip", "\\foreach", "\\angle", "\\coordinate", \ "\\useasboundingbox", "\\tikztostart", "\\tikztotarget", "\\tikztonodes", "\\tikzlastnode", \ "\\pgfextra", "\\endpgfextra", "\\verb", "\\coordinate", \ "\\pattern", "\\shade", "\\shadedraw", "\\colorlet", "\\definecolor", \ "\\pgfmatrixnextcell" ] let g:atp_tikz_keywords=[ 'draw', 'node', 'matrix', 'anchor', 'top', 'bottom', \ 'west', 'east', 'north', 'south', 'at', 'thin', 'thick', 'semithick', 'rounded', 'corners', \ 'controls', 'and', 'circle', 'step', 'grid', 'very', 'style', 'line', 'help', \ 'color', 'arc', 'curve', 'scale', 'parabola', 'line', 'ellipse', 'bend', 'sin', 'rectangle', 'ultra', \ 'right', 'left', 'intersection', 'xshift', 'yshift', 'shift', 'near', 'start', 'above', 'below', \ 'end', 'sloped', 'coordinate', 'cap', 'shape', 'label', 'every', \ 'edge', 'point', 'loop', 'join', 'distance', 'sharp', 'rotate', 'blue', 'red', 'green', 'yellow', \ 'black', 'white', 'gray', \ 'text', 'width', 'inner', 'sep', 'baseline', 'current', 'bounding', 'box', \ 'canvas', 'polar', 'radius', 'barycentric', 'angle', 'opacity', \ 'solid', 'phase', 'loosly', 'dashed', 'dotted' , 'densly', \ 'latex', 'diamond', 'double', 'smooth', 'cycle', 'coordinates', 'distance', \ 'even', 'odd', 'rule', 'pattern', \ 'stars', 'shading', 'ball', 'axis', 'middle', 'outer', 'transorm', \ 'fading', 'horizontal', 'vertical', 'light', 'dark', 'button', 'postaction', 'out', \ 'circular', 'shadow', 'scope', 'borders', 'spreading', 'false', 'position', 'midway', \ 'paint', 'from', 'to' ] let g:atp_tikz_library_arrows_keywords = [ 'reversed', 'stealth', 'triangle', 'open', \ 'hooks', 'round', 'fast', 'cap', 'butt'] let g:atp_tikz_library_automata_keywords=[ 'state', 'accepting', 'initial', 'swap', \ 'loop', 'nodepart', 'lower', 'upper', 'output'] let g:atp_tikz_library_backgrounds_keywords=[ 'background', 'show', 'inner', 'frame', 'framed', \ 'tight', 'loose', 'xsep', 'ysep'] let g:atp_tikz_library_calendar_commands=[ '\calendar', '\tikzmonthtext' ] let g:atp_tikz_library_calendar_keywords=[ 'week list', 'dates', 'day', 'day list', 'month', 'year', 'execute', \ 'before', 'after', 'downward', 'upward' ] let g:atp_tikz_library_chain_commands=[ '\chainin' ] let g:atp_tikz_library_chain_keywords=[ 'chain', 'start chain', 'on chain', 'continue chain', \ 'start branch', 'branch', 'going', 'numbers', 'greek' ] let g:atp_tikz_library_decorations_commands=[ '\\arrowreversed' ] let g:atp_tikz_library_decorations_keywords=[ 'decorate', 'decoration', 'lineto', 'straight', 'zigzag', \ 'saw', 'random steps', 'bent', 'aspect', 'bumps', 'coil', 'curveto', 'snake', \ 'border', 'brace', 'segment lenght', 'waves', 'ticks', 'expanding', \ 'crosses', 'triangles', 'dart', 'shape', 'width', 'size', 'sep', 'shape backgrounds', \ 'between', 'along', 'path', \ 'Koch curve type 1', 'Koch curve type 1', 'Koch snowflake', 'Cantor set', 'footprints', \ 'foot', 'stride lenght', 'foot', 'foot', 'foot of', 'gnome', 'human', \ 'bird', 'felis silvestris', 'evenly', 'spread', 'scaled', 'star', 'height', 'text', \ 'mark', 'reset', 'marks' ] let g:atp_tikz_library_er_keywords = [ 'entity', 'relationship', 'attribute', 'key'] let g:atp_tikz_library_fadings_keywords = [ 'with', 'fuzzy', 'percent', 'ring' ] let g:atp_tikz_library_fit_keywords = [ 'fit'] let g:atp_tikz_library_matrix_keywords = ['matrix', 'of', 'nodes', 'math', 'matrix of math nodes', \ 'matrix of nodes', 'delimiter', \ 'rmoustache', 'column sep=', 'row sep=' ] let g:atp_tikz_library_mindmap_keywords = [ 'mindmap', 'concept', 'large', 'huge', 'extra', 'root', 'level', \ 'connection', 'bar', 'switch', 'annotation' ] let g:atp_tikz_library_folding_commands = ["\\tikzfoldingdodecahedron"] let g:atp_tikz_library_folding_keywords = ['face', 'cut', 'fold'] let g:atp_tikz_library_patterns_keywords = ['lines', 'fivepointed', 'sixpointed', 'bricks', 'checkerboard', \ 'crosshatch', 'dots'] let g:atp_tikz_library_petri_commands = ["\\tokennumber" ] let g:atp_tikz_library_petri_keywords = ['place', 'transition', 'pre', 'post', 'token', 'child', 'children', \ 'are', 'tokens', 'colored', 'structured' ] let g:atp_tikz_library_pgfplothandlers_commands = ["\\pgfplothandlercurveto", "\\pgfsetplottension", \ "\\pgfplothandlerclosedcurve", "\\pgfplothandlerxcomb", "\\pgfplothandlerycomb", \ "\\pgfplothandlerpolarcomb", "\\pgfplothandlermark{", "\\pgfsetplotmarkpeat{", \ "\\pgfsetplotmarkphase", "\\pgfplothandlermarklisted{", "\\pgfuseplotmark", \ "\\pgfsetplotmarksize{", "\\pgfplotmarksize" ] let g:atp_tikz_library_plotmarks_keywords = [ 'asterisk', 'star', 'oplus', 'oplus*', 'otimes', 'otimes*', \ 'square', 'square*', 'triangle', 'triangle*', 'diamond*', 'pentagon', 'pentagon*'] let g:atp_tikz_library_shadow_keywords = ['general shadow', 'shadow', 'drop shadow', 'copy shadow', 'glow' ] let g:atp_tikz_library_shapes_keywords = ['shape', 'center', 'base', 'mid', 'trapezium', 'semicircle', 'chord', 'regular polygon', 'corner', 'star', 'isoscales triangle', 'border', 'stretches', 'kite', 'vertex', 'side', 'dart', 'tip', 'tail', 'circular', 'sector', 'cylinder', 'minimum', 'height', 'width', 'aspect', 'uses', 'custom', 'body', 'forbidden sign', 'cloud', 'puffs', 'ignores', 'starburst', 'random', 'signal', 'pointer', 'tape', \ 'single', 'arrow', 'head', 'extend', 'indent', 'after', 'before', 'arrow box', 'shaft', \ 'lower', 'upper', 'split', 'empty', 'part', \ 'callout', 'relative', 'absolute', 'shorten', \ 'logic gate', 'gate', 'inputs', 'inverted', 'radius', 'use', 'US style', 'CDH style', 'nand', 'and', 'or', 'nor', 'xor', 'xnor', 'not', 'buffer', 'IEC symbol', 'symbol', 'align', \ 'cross out', 'strike out', 'length', 'chamfered rectangle' ] let g:atp_tikz_library_topath_keywords = ['line to', 'curve to', 'out', 'in', 'relative', 'bend', 'looseness', 'min', 'max', 'control', 'loop'] let g:atp_tikz_library_through_keywords = ['through'] let g:atp_tikz_library_trees_keywords = ['grow', 'via', 'three', 'points', 'two', 'child', 'children', 'sibling', 'clockwise', 'counterclockwise', 'edge', 'parent', 'fork'] " BEAMER let g:atp_BeamerEnvironments = ["frame", "beamercolorbox", "onlyenv", "altenv", \ "visibleenv", "uncoverenv", "invisibleenv", "overlayarea", "overprint", "actionenv", \ 'description', 'structureenv', 'alertenv', 'block', 'alertblock', 'exampleblock', 'beamercolorbox', \ 'beamerboxesrounded', 'columns', 'semiverbatim' ] let g:atp_BeamerCommands = ["\\alert{", "\\frametitle{", "\\framesubtitle", "\\titlepage", "\\setbeamercolor{", \ "\\pauze", "\\onslide", "\\only", "\\uncover", "\\visible", "\\invisible", "\\temporal", "\\alt", \ "\\usebeamercolor{", "\\usetheme{", "\\includeonlyframes{", "\\againframe", "\\setbeamersize{", \ "\\action{", "\\inserttocsection", "\\inserttocsectionumber", "\\lecture", "\\AtBeginLecture{", \ "\\appendix", "\\hypertarget", "\\beamerbutton", "\\beamerskipbutton", "\\beamerreturnbutton", \ "\\beamergotobutton", '\hyperlinkslideprev', '\hyperlinkslidenext', '\hyperlinkframestart', \ '\hyperlinkframeend', '\hyperlinkframestartnext', '\hyperlinkframeendprev', \ '\hyperlinkpresentationstart', '\hyperlinkpresentationend', '\hyperlinkappendixstart', \ '\hyperlinkappendixend', '\hyperlinkdocumentstart', '\hyperlinkdocumentend', \ '\framezoom', '\structure', '\insertblocktitle', '\column', '\movie', '\animate', \ '\hyperlinksound', '\hyperlinkmute', \ '\usetheme', '\usecolortheme', '\usefonttheme', '\useinnertheme', '\useoutertheme', \ '\usefonttheme', '\note', '\AtBeginNote', '\AtEndNote', '\setbeameroption{', \ '\setbeamerfont{', '\mode' ] let g:atp_BeamerThemes = [ "default", "boxes", "Bergen", "Boadilla", "Madrid", "AnnArbor", \ "CambridgeUS", "Pittsburgh", "Rochester", "Antibes", "JuanLesPins", "Montpellier", \ "Berkeley" , "PalAlto", "Gottingen", "Marburg", "Hannover", "Berlin", "Ilmenau", \ "Dresden", "Darmstadt", "Frankfurt", "Singapore", "Szeged", "Copenhagen", "Luebeck", "Malmoe", \ "Warsaw", ] let g:atp_BeamerInnerThemes = [ "default", "circles", "rectangles", "rounded", "inmargin" ] let g:atp_BeamerOuterThemes = [ "default", "infolines", "miniframes", "smoothbars", "sidebar", \ "split", "shadow", "tree", "smoothtree" ] let g:atp_BeamerColorThemes = [ "default", "structure", "sidebartab", "albatross", "beetle", "crane", \ "dove", "fly", "seagull", "wolverine", "beaver", "lily", "orchid", "rose", "whale", "seahorse", \ "dolphin" ] let g:atp_BeamerFontThemes = [ "default", "serif", "structurebold", "structureitalicserif", \ "structuresmallcapsserif" ] let g:atp_MathTools_math_commands = [ '\cramped', '\crampedllap', '\crampedclap', '\crampedrlap', '\smashoperator', \ '\adjustlimits', '\newtagform{', '\usetagform{', '\renewtagform{', \ '\xleftrightarrow', '\xRightarrow', '\xLeftarrow', '\xLeftrightarrow', \ '\xhookleftarrow', '\xhookrightarrow', '\xmapsto', '\underbracket', '\overbracket', \ '\LaTeXunderbrace', '\LaTeXoverbrace', '\Aboxed', '\ArrowBetweenLines', '\ArrowBetweenLines*', \ '\shortintertext', '\lparen', '\rparen', '\vcentcolon', \ '\ordinarycolon', '\mathtoolsset{', '\prescript', \ '\newgathered', '\renewgathered', '\splitfrac{', '\splitdfrac{' ] let g:atp_MathTools_commands = [ '\DeclarePairedDelimiter{', '\DeclarePairedDelimiterX{' ] let g:atp_MathTools_environments = [ 'matrix*', 'pmatrix*', 'bmatrix*', 'Bmatrix*', 'vmatrix*', 'Vmatrix*', \ 'multilined', 'dcases', 'dcases*', 'rcases', 'rcases*', 'drcases*', 'cases*', 'spreadlines', \ 'lgathered', 'rgathered' ] let g:atp_TodoNotes_commands = [ '\todo{', '\listoftodos', '\missingfigure' ] let g:atp_TodoNotes_todo_options = [ 'disable', 'color=', 'backgroundcolor=', 'linecolor=', 'bordercolor=', \ 'line', 'noline', 'inline', 'noinline', 'size=', 'list', 'nolist', \ 'caption=', 'prepend', 'noprepend', 'fancyline'] let g:atp_TodoNotes_missingfigure_options = [ 'figwidth=' ] if !exists("g:atp_MathOpened") || g:atp_reload let g:atp_MathOpened = 1 endif " augroup ATP_MathOpened " au! " au Syntax tex :let g:atp_MathOpened = 1 " augroup END let g:atp_math_modes=[ ['\%([^\\]\|^\)\%(\\\|\\\{3}\)(','\%([^\\]\|^\)\%(\\\|\\\{3}\)\zs)'], \ ['\%([^\\]\|^\)\%(\\\|\\\{3}\)\[','\%([^\\]\|^\)\%(\\\|\\\{3}\)\zs\]'], \ ['\\begin{align', '\\end{alig\zsn'], ['\\begin{gather', '\\end{gathe\zsr'], \ ['\\begin{falign', '\\end{flagi\zsn'], ['\\begin[multline', '\\end{multlin\zse'], \ ['\\begin{equation', '\\end{equatio\zsn'], \ ['\\begin{\%(display\)\?math', '\\end{\%(display\)\?mat\zsh'] ] " Completion variables for \pagestyle{} and \thispagestyle{} LaTeX commands. let g:atp_pagestyles = [ 'plain', 'headings', 'empty', 'myheadings' ] let g:atp_fancyhdr_pagestyles = [ 'fancy' ] " Completion variable for \pagenumbering{} LaTeX command. let g:atp_pagenumbering = [ 'arabic', 'roman', 'Roman', 'alph', 'Alph' ] " }}} " " Some of the autocommands (Status Line, LocalCommands, Log File): " {{{ Autocommands: if !s:did_options augroup ATP_deltmpdir au VimLeave *.tex :call system("rmdir " . b:atp_TmpDir) augroup END augroup ATP_updatetime au VimEnter if &l:updatetime == 4000 | let &l:updatetime = 800 | endif au InsertEnter *.tex let s:updatetime=&l:updatetime | let &l:updatetime = g:atp_insert_updatetime au InsertLeave *.tex let &l:updatetime=s:updatetime augroup END if (exists("g:atp_statusline") && g:atp_statusline == '1') || !exists("g:atp_statusline") augroup ATP_Status au! au BufWinEnter *.tex call ATPStatus("") augroup END endif if g:atp_local_completion == 2 augroup ATP_LocaCommands au! au BufEnter *.tex call LocalCommands() augroup END endif augroup ATP_TeXFlavor au! au FileType *tex let b:atp_TexFlavor = &filetype augroup END " Idea: " au *.log if LogBufferFileDiffer | silent execute '%g/^\s*$/d' | w! | endif " or maybe it is better to do that after latex made the log file in the call back " function, but this adds something to every compilation process ! " This changes the cursor position in the log file which is NOT GOOD. " au WinEnter *.log execute "normal m'" | silent execute '%g/^\s*$/d' | execute "normal ''" " Experimental: " This doesn't work ! " let g:debug=0 " fun! GetSynStackI() " let synstack=[] " let synstackI=synstack(line("."), col(".")) " try " let test = synstackI == 0 " let b:return = 1 " catch /Can only compare List with List/ " let b:return = 0 " endtry " if b:return == 0 " return [] " else " let g:debug+= 1 " return map(synstack, "synIDattr(v:val, 'name')") " endif " endfunction " The first one is not working! (which is the more important of these two :( " au CursorMovedI *.tex let g:atp_synstackI = GetSynStackI() " This has problems in visual mode: " au CursorMoved *.tex let g:atp_synstack = map(synstack(line('.'), col('.')), "synIDattr(v:val, 'name')") endif " }}} " This function and the following autocommand toggles the textwidth option if " editing a math mode. Currently, supported are $:$, \(:\), \[:\] and $$:$$. " {{{ SetMathVimOptions if !exists("g:atp_SetMathVimOptions") || g:atp_reload let g:atp_SetMathVimOptions = 1 endif if !exists("g:atp_MathVimOptions") || g:atp_reload " { 'option_name' : [ val_in_math, normal_val], ... } let g:atp_MathVimOptions = { 'textwidth' : [ 0, &textwidth], \ } endif if !exists("g:atp_MathZones") || g:atp_reload let g:atp_MathZones = &l:filetype == "tex" ? [ \ 'texMathZoneV', 'texMathZoneW', \ 'texMathZoneX', 'texMathZoneY', \ 'texMathZoneA', 'texMathZoneAS', \ 'texMathZoneB', 'texMathZoneBS', \ 'texMathZoneC', 'texMathZoneCS', \ 'texMathZoneD', 'texMathZoneDS', \ 'texMathZoneE', 'texMathZoneES', \ 'texMathZoneF', 'texMathZoneFS', \ 'texMathZoneG', 'texMathZoneGS', \ 'texMathZoneH', 'texMathZoneHS', \ 'texMathZoneI', 'texMathZoneIS', \ 'texMathZoneJ', 'texMathZoneJS', \ 'texMathZoneK', 'texMathZoneKS', \ 'texMathZoneL', 'texMathZoneLS', \ 'texMathZoneT' \ ] \ : [ 'plaintexMath' ] endif " a:0 = 0 check if in math mode " a:1 = 0 assume cursor is not in math " a:1 = 1 assume cursor stands in math function! s:SetMathVimOptions(...) if !g:atp_SetMathVimOptions return "no setting to toggle" endif let MathZones = copy(g:atp_MathZones) if b:atp_TexFlavor == 'plaintex' call add(MathZones, 'texMathZoneY') endif " Change the long values to numbers let MathVimOptions = map(copy(g:atp_MathVimOptions), \ " v:val[0] =~ v:key ? [ v:val[0] =~ '^no' . v:key ? 0 : 1, v:val[1] ] : v:val " ) let MathVimOptions = map(MathVimOptions, \ " v:val[1] =~ v:key ? [ v:val[0], v:val[1] =~ '^no' . v:key ? 0 : 1 ] : v:val " ) " check if the current (and 3 steps back) cursor position is in math " or use a:1 let check = a:0 == 0 ? atplib#CheckSyntaxGroups(MathZones) + atplib#CheckSyntaxGroups(MathZones, line("."), max([ 1, col(".")-3])) : a:1 if check for option_name in keys(MathVimOptions) execute "let &l:".option_name. " = " . MathVimOptions[option_name][0] endfor else for option_name in keys(MathVimOptions) execute "let &l:".option_name. " = " . MathVimOptions[option_name][1] endfor endif endfunction if !s:did_options augroup ATP_SetMathVimOptions au! " if leaving the insert mode set the non-math options au InsertLeave *.tex :call s:SetMathVimOptions(0) " if entering the insert mode or in the insert mode check if the cursor is in " math or not and set the options acrodingly au InsertEnter *.tex :call s:SetMathVimOptions() au CursorMovedI *.tex :call s:SetMathVimOptions() " This slows down vim when moving the cursor: " au CursorMoved *.tex :call s:SetMathVimOptions() augroup END endif "}}} " Add extra syntax groups " {{{1 ATP_SyntaxGroups function! s:ATP_SyntaxGroups() if atplib#SearchPackage('tikz') || atplib#SearchPackage('pgfplots') try call TexNewMathZone("T", "tikzpicture", 0) catch /E117:/ endtry endif if atplib#SearchPackage('algorithmic') try call TexNewMathZone("ALG", "algorithmic", 0) catch /E117:/ endtry endif endfunction augroup ATP_Syntax_TikzZone au Syntax tex :call ATP_SyntaxGroups() augroup END augroup ATP_Devel au BufEnter *.sty :setl nospell au BufEnter *.cls :setl nospell au BufEnter *.fd :setl nospell augroup END "}}}1 "{{{1 Highlightings in help file augroup ATP_HelpFile_Highlight au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_FileName') ? "atp_FileName" : "Title", 'highlight atp_FileName\s\+Title') au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_LineNr') ? "atp_LineNr" : "LineNr", 'highlight atp_LineNr\s\+LineNr') au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_Number') ? "atp_Number" : "Number", 'highlight atp_Number\s\+Number') au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_Chapter') ? "atp_Chapter" : "Label", 'highlight atp_Chapter\s\+Label') au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_Section') ? "atp_Section" : "Label", 'highlight atp_Section\s\+Label') au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_SubSection') ? "atp_SubSection": "Label", 'highlight atp_SubSection\s\+Label') au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_Abstract') ? "atp_Abstract" : "Label", 'highlight atp_Abstract\s\+Label') au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_label_FileName') ? "atp_label_FileName" : "Title", '^\s*highlight atp_label_FileName\s\+Title\s*$') au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_label_LineNr') ? "atp_label_LineNr" : "LineNr", '^\s*highlight atp_label_LineNr\s\+LineNr\s*$') au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_label_Name') ? "atp_label_Name" : "Label", '^\s*highlight atp_label_Name\s\+Label\s*$') au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('atp_label_Counter') ? "atp_label_Counter" : "Keyword", '^\s*highlight atp_label_Counter\s\+Keyword\s*$') au BufEnter automatic-tex-plugin.txt call matchadd(hlexists('bibsearchInfo') ? "bibsearchInfo" : "Number", '^\s*highlight bibsearchInfo\s*$') augroup END "}}}1 " {{{1 :Viewer, :Compiler, :DebugMode function! s:Viewer(viewer) let old_viewer = b:atp_Viewer let oldViewer = get(g:ViewerMsg_Dict, matchstr(old_viewer, '^\s*\zs\S*'), "") let b:atp_Viewer = a:viewer let Viewer = get(g:ViewerMsg_Dict, matchstr(b:atp_Viewer, '^\s*\zs\S*'), "") silent! execute "aunmenu LaTeX.View\\ with\\ ".oldViewer silent! execute "aunmenu LaTeX.View\\ Output" if Viewer != "" execute "menu 550.10 LaTe&X.&View\\ with\\ ".Viewer.":ViewOutput :ViewOutput" execute "cmenu 550.10 LaTe&X.&View\\ with\\ ".Viewer.":ViewOutput ViewOutput" execute "imenu 550.10 LaTe&X.&View\\ with\\ ".Viewer.":ViewOutput :ViewOutputa" else execute "menu 550.10 LaTe&X.&View\\ Output\\ :ViewOutput :ViewOutput" execute "cmenu 550.10 LaTe&X.&View\\ Output\\ :ViewOutput ViewOutput" execute "imenu 550.10 LaTe&X.&View\\ Output\\ :ViewOutput :ViewOutputa" endif endfunction command! -buffer -nargs=1 -complete=customlist,ViewerComp Viewer :call Viewer() function! ViewerComp(A,L,P) let view = [ 'okular', 'xpdf', 'xdvi', 'evince', 'epdfview', 'kpdf', 'acroread', 'zathura' ] call filter(view, "v:val =~ '^' . a:A") call filter(view, 'executable(v:val)') return view endfunction function! s:Compiler(compiler) let old_compiler = b:atp_TexCompiler let oldCompiler = get(g:CompilerMsg_Dict, matchstr(old_compiler, '^\s*\zs\S*'), "") let b:atp_TexCompiler = a:compiler let Compiler = get(g:CompilerMsg_Dict, matchstr(b:atp_TexCompiler, '^\s*\zs\S*'), "") silent! execute "aunmenu LaTeX.".oldCompiler silent! execute "aunmenu LaTeX.".oldCompiler."\\ debug" silent! execute "aunmenu LaTeX.".oldCompiler."\\ twice" execute "menu 550.5 LaTe&X.&".Compiler.":TEX :TEX" execute "cmenu 550.5 LaTe&X.&".Compiler.":TEX TEX" execute "imenu 550.5 LaTe&X.&".Compiler.":TEX :TEXa" execute "menu 550.6 LaTe&X.".Compiler."\\ debug:TEX\\ debug :DTEX" execute "cmenu 550.6 LaTe&X.".Compiler."\\ debug:TEX\\ debug DTEX" execute "imenu 550.6 LaTe&X.".Compiler."\\ debug:TEX\\ debug :DTEXa" execute "menu 550.7 LaTe&X.".Compiler."\\ &twice:2TEX :2TEX" execute "cmenu 550.7 LaTe&X.".Compiler."\\ &twice:2TEX 2TEX" execute "imenu 550.7 LaTe&X.".Compiler."\\ &twice:2TEX :2TEXa" endfunction command! -buffer -nargs=1 -complete=customlist,CompilerComp Compiler :call Compiler() function! CompilerComp(A,L,P) let compilers = [ 'tex', 'pdftex', 'latex', 'pdflatex', 'etex', 'xetex', 'luatex' ] " let g:compilers = copy(compilers) call filter(compilers, "v:val =~ '^' . a:A") call filter(compilers, 'executable(v:val)') return compilers endfunction command! -buffer -nargs=1 -complete=customlist,DebugComp DebugMode :let t:atp_DebugMode= function! DebugComp(A,L,P) let modes = [ 'silent', 'debug', 'verbose'] call filter(modes, "v:val =~ '^' . a:A") return modes endfunction "}}}1 " vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1 ftplugin/ATP_files/search.vim [[[1 1205 " Author: Marcin Szamotulski " Description: This file provides searching tools of ATP. " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " Language: tex " Last Change: let s:sourced = exists("s:sourced") ? 1 : 0 " Functions: (soure once) if !s:sourced || g:atp_reload_functions "{{{ " Make a dictionary of definitions found in all input files. " {{{ s:make_defi_dict " Comparing with ]D, ]d, ]i, ]I vim maps this function deals with multiline " definitions. " " The output dictionary is of the form: " { input_file : [ [begin_line, end_line], ... ] } " a:1 = buffer name to search in for input files " a:3 = 1 skip searching for the end_line " " ToDo: it is possible to check for the end using searchpairpos, but it " operates on a list not on a buffer. function! s:make_defi_dict(bang,...) let atp_MainFile = atplib#FullPath(b:atp_MainFile) let bufname = a:0 >= 1 ? a:1 : atp_MainFile " pattern to match the definitions this function is also used to fine " \newtheorem, and \newenvironment commands let pattern = a:0 >= 2 ? a:2 : '\\def\|\\newcommand' let preambule_only= a:bang == "!" ? 0 : 1 " this is still to slow! let only_begining = a:0 >= 3 ? a:3 : 0 let defi_dict={} let inputfiles=FindInputFiles(bufname) let input_files=[] " TeX: How this work in TeX files. for inputfile in keys(inputfiles) if inputfiles[inputfile][0] != "bib" && ( !preambule_only || inputfiles[inputfile][0] == "preambule" ) call add(input_files, inputfiles[inputfile][2]) endif endfor let input_files=filter(input_files, 'v:val != ""') if !count(input_files, atp_MainFile) call extend(input_files,[ atp_MainFile ]) endif if len(input_files) > 0 for inputfile in input_files let defi_dict[inputfile]=[] " do not search for definitions in bib files "TODO: it skips lines somehow. let ifile=readfile(inputfile) " search for definitions let lnr=1 while (lnr <= len(ifile) && (!preambule_only || ifile[lnr-1] !~ '\\begin\s*{document}')) let match=0 let line=ifile[lnr-1] if substitute(line,'\\\@ renegenerate the input files. function! LocalCommands(...) " let time = reltime() let pattern = a:0 >= 1 && a:1 != '' ? a:1 : '\\def\>\|\\newcommand\>\|\\newenvironment\|\\newtheorem\|\\definecolor\|' \ . '\\Declare\%(RobustCommand\|FixedFont\|TextFontCommand\|MathVersion\|SymbolFontAlphabet' \ . '\|MathSymbol\|MathDelimiter\|MathAccent\|MathRadical\|MathOperator\)' \ . '\|\\SetMathAlphabet\>' let bang = a:0 >= 2 ? a:2 : '' " Regenerate the package list if bang == "!" let b:atp_PacakgeList = atplib#GrepPackageList() endif let atp_MainFile = atplib#FullPath(b:atp_MainFile) " Makeing lists of commands and environments found in input files if bang == "!" || !exists("b:TreeOfFiles") " Update the cached values: let [ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ] = TreeOfFiles(atp_MainFile) endif let [ Tree, List, Type_Dict, Level_Dict ] = deepcopy([ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ]) let saved_loclist = getloclist(0) " I should scan the preambule separately! " This will make the function twice as fast! silent! execute "lvimgrep /".pattern."/j " . fnameescape(atp_MainFile) for file in List if get(Type_Dict, file, 'no_file') == 'preambule' silent! execute "lvimgrepadd /".pattern."/j " . fnameescape(file) endif endfor let loclist = getloclist(0) call setloclist(0, saved_loclist) let atp_LocalCommands = [] let atp_LocalEnvironments = [] let atp_LocalColors = [] for line in loclist " the order of pattern is important if line['text'] =~ '\\definecolor' " color name let name=matchstr(line['text'], \ '\\definecolor\s*{\s*\zs[^}]*\ze\s*}') let type="Colors" elseif line['text'] =~ '\\def\>\|\\newcommand' " definition name let name= '\' . matchstr(line['text'], \ '\\def\\\zs[^{#]*\ze[{#]\|\\newcommand{\?\\\zs[^\[{]*\ze}') let type="Commands" " definition " let def=matchstr(line['text'], " \ '^\%(\\def\\[^{]*{\zs.*\ze}\|\\newcommand\\[^{]*{\zs.*\ze}\)') elseif line['text'] =~ '\\Declare\%(RobustCommand\|FixedFont\|TextFontCommand\|MathVersion\|SymbolFontAlphabet' \ . '\|MathSymbol\|MathDelimiter\|MathAccent\|MathRadical\|MathOperator\)\>\|\\SetMathAlphabet' let name=matchstr(line['text'], \ '\%(\\Declare\%(RobustCommand\|FixedFont\|TextFontCommand\|MathVersion\|SymbolFontAlphabet' \ . '\|MathSymbol\|MathDelimiter\|MathAccent\|MathRadical\|MathOperator\)\|\\SetMathAlphabet\)\s*{\s*\zs[^}]*\ze\s*}') let type="Commands" elseif line['text'] =~ '\%(\\newenvironment\|\\newtheorem\)' " environment name let name=matchstr(line['text'], \ '\\\%(newtheorem\*\?\|newenvironment\)\s*{\s*\zs[^}]*\ze\s*}') let type="Environments" endif if exists("name") && name != '' && name != '\' if count(atp_Local{type}, name) == 0 call add(atp_Local{type}, name) endif endif endfor let b:atp_LocalCommands = atp_LocalCommands let b:atp_LocalEnvironments = atp_LocalEnvironments let b:atp_LocalColors = atp_LocalColors " echomsg reltimestr(reltime(time)) return [ atp_LocalEnvironments, atp_LocalCommands, atp_LocalColors ] endfunction "}}} " Search for Definition in the definition dictionary (s:make_defi_dict). "{{{ DefiSearch function! DefiSearch(bang,...) let pattern = a:0 >= 1 ? a:1 : '' let preambule_only = a:bang == "!" ? 0 : 1 let atp_MainFile = atplib#FullPath(b:atp_MainFile) let defi_dict = s:make_defi_dict(a:bang, atp_MainFile, '\\def\|\\newcommand') " open new buffer let openbuffer=" +setl\\ buftype=nofile\\ nospell " . fnameescape("DefiSearch") if g:vertical ==1 let openbuffer="keepalt vsplit " . openbuffer else let openbuffer="keepalt split " . openbuffer endif if len(defi_dict) > 0 " wipe out the old buffer and open new one instead if bufloaded("DefiSearch") exe "silent bd! " . bufnr("DefiSearch") endif silent exe openbuffer let b:atp_MainFile = expand("%") let b:atp_ProjectDir = expand("%:p:h") setl syntax=tex map q :bd for inputfile in keys(defi_dict) let ifile = readfile(inputfile) for l:range in defi_dict[inputfile] " This respects the options 'smartcase' and 'ignorecase'. let case = ( &l:smartcase && &l:ignorecase && pattern =~ '\u' ? 'noignorecase' : ( &l:ignorecase ? 'ignorecase' : 'noignorecase' )) let condition = ( case == "noignorecase" ? ifile[l:range[0]-1] =~# pattern : ifile[l:range[0]-1] =~? pattern ) if condition " print the lines into the buffer let i=0 let c=0 " add an empty line if the definition is longer than one line if l:range[0] != l:range[1] call setline(line('$')+1,'') let i+=1 endif while c <= l:range[1]-l:range[0] let line=l:range[0]+c call setline(line('$')+1,ifile[line-1]) let i+=1 let c+=1 endwhile endif endfor endfor if getbufline("DefiSearch",'1','$') == [''] :bw redraw echohl ErrorMsg echomsg "Definition not found." echohl Normal endif else redraw echohl ErrorMsg echomsg "Definition not found." echohl Normal endif endfunction "}}} " Search in tree and return the one level up element and its line number. " {{{ SearchInTree " Before running this function one has to set the two variables " s:branch/s:branch_line to 0. " the a:tree variable should be something like: " a:tree = { b:atp_MainFile, [ TreeOfFiles(b:atp_MainFile)[0], 0 ] } " necessary a rooted tree! " This function remaps keys of dictionary. function! MapDict(dict) let new_dict = {} for key in keys(a:dict) let new_key = fnamemodify(key, ":p") let new_dict[new_key] = a:dict[key] endfor return new_dict endfunction function! SearchInTree(tree, branch, what) if g:atp_debugSIT redir! >> /tmp/atp_debugSIT silent! echo "___SEARCH_IN_TREE___" silent! echo "a:branch=". a:branch silent! echo "a:what=" . a:what endif if g:atp_debugSIT >= 2 silent! echo "a:tree=" . string(a:tree) endif " let branch = a:tree[a:branch][0] if a:branch =~ '^\s*\/' let cwd = getcwd() exe "lcd " . fnameescape(b:atp_ProjectDir) let branchArg = ( g:atp_RelativePath ? fnamemodify(a:branch, ":.") : a:branch ) let branchArgN = ( !g:atp_RelativePath ? fnamemodify(a:branch, ":.") : a:branch ) let whatArg = ( g:atp_RelativePath ? fnamemodify(a:what, ":.") : a:what ) let whatArgN = ( !g:atp_RelativePath ? fnamemodify(a:what, ":.") : a:what ) if g:atp_debugSIT silent! echo "*** cwd=" . getcwd() . " b:atp_ProjectDir= " . b:atp_ProjectDir . " " . fnamemodify(a:branch, ":.") . " " . a:branch endif exe "lcd " . fnameescape(cwd) else let branchArg = ( g:atp_RelativePath ? a:branch : atplib#FullPath(a:branch) ) let branchArgN = ( !g:atp_RelativePath ? a:branch : atplib#FullPath(a:branch) ) let whatArg = ( g:atp_RelativePath ? a:what : atplib#FullPath(a:what) ) let whatArgN = ( !g:atp_RelativePath ? a:what : atplib#FullPath(a:what) ) endif if g:atp_debugSIT silent! echo "branchArg=" . branchArg . " branchArgN=" . branchArgN silent! echo "whatArg=" . whatArg . " whatArgN=" . whatArgN endif let branch = get(a:tree, branchArg , get(a:tree, branchArgN, ['NO_BRANCH']))[0] if count(keys(branch), whatArg) || count(keys(branch), whatArgN) " The following variable is used as a return value in " RecursiveSearch! let g:ATP_branch = branchArg " let g:ATP_branch_line = a:tree[a:branch][0][a:what][1] let g:ATP_branch_line = get(branch, whatArg, get(branch, whatArgN, ['', 'ERROR']))[1] if g:atp_debugSIT silent! echo "g:ATP_branch=" . g:ATP_branch . " g:ATP_branch_line=" . g:ATP_branch_line redir END endif return branchArg " return a:branch else for new_branch in keys(branch) call SearchInTree(branch, new_branch, whatArg) endfor endif if g:atp_debugSIT redir END endif return "X" endfunction " }}} " Search in all input files recursively. " {{{ Search (recursive) " " Variables are used to pass them to next runs (this function calls it self) " a:main_file = b:atp_MainFile " a:start_file = expand("%:p") /this variable will not change untill the " last instance/ " a:tree = make_tree => make a tree " = any other value => use { a:main_file : [ b:TreeOfFiles, 0] } " a:cur_branch = expand("%") /this will change whenever we change a file/ " a:call_nr = number of the call " a:wrap_nr = if hit top/bottom a:call=0 but a:wrap_nr+=1 " a:winsaveview = winsaveview(0) to resotre the view if the pattern was not found " a:bufnr = bufnr("%") to come back to begining buffer if pattern not found " a:strftime = strftime(0) to compute the time " a:pattern = pattern to search " a:1 = flags: 'bcewWs' " a:2 is not not used: " a:2 = goto = DOWN_ACCEPT / Must not be used by the end user/ " 0/1 1=DOWN_ACCEPT " " g:atp_debugRS if 1 sets debugging messages which are appended to '/tmp/ATP_rs_debug' " you can :set errorfile=/tmp/ATP_rs_debug " and :set efm=.* " if 2 show time " log file : /tmp/ATP_rs_debug " {{{ s:RecursiveSearch function let g:atp_swapexists = 0 try function! RecursiveSearch(main_file, start_file, maketree, tree, cur_branch, call_nr, wrap_nr, winsaveview, bufnr, strftime, vim_options, cwd, pattern, ... ) let main_file = g:atp_RelativePath ? atplib#RelativePath(a:main_file, b:atp_ProjectDir) : a:main_file let time0 = reltime() " set and restore some options: " foldenable (unset to prevent opening the folds :h winsaveview) " comeback to the starting buffer if a:call_nr == 1 && a:wrap_nr == 1 if a:vim_options == { 'no_options' : 'no_options' } let vim_options = { 'hidden' : &l:hidden, \ 'foldenable' : &l:foldenable, \ 'autochdir' : &l:autochdir } else let vim_options = a:vim_options endif let &l:hidden = 1 let &l:foldenable = 0 let &l:autochdir = 0 if a:cwd == 'no_cwd' let cwd = getcwd() else let cwd = a:cwd endif exe "lcd " . fnameescape(b:atp_ProjectDir) " This makes it work faster when the input files were not yet opened by vim " some of them will not be shown to the user. " syntax off filetype off " there are many errors in /tmp/ATP_rs_debug file due to this which are not " important. else let vim_options = a:vim_options let cwd = a:cwd endif " Redirect debuggin messages: if g:atp_debugRS if a:wrap_nr == 1 && a:call_nr == 1 redir! > /tmp/ATP_rs_debug else redir! >> /tmp/ATP_rs_debug endif silent echo "________________" silent echo "Args: a:pattern:".a:pattern." call_nr:".a:call_nr. " wrap_nr:".a:wrap_nr . " cwd=" . getcwd() endif let flags_supplied = a:0 >= 1 ? a:1 : "" if flags_supplied =~# 'p' let flags_supplied = substitute(flags_supplied, 'p', '', 'g') echohl WarningMsg echomsg "Searching flag 'p' is not supported, filtering it out." echohl Normal endif if a:maketree == 'make_tree' if g:atp_debugRS silent echo "*** Makeing Tree ***" endif let tree_of_files = TreeOfFiles(main_file)[0] else if g:atp_debugRS silent echo "*** Using Tree ***" endif let tree_of_files = a:tree endif let tree = { main_file : [ tree_of_files, 0 ] } if a:cur_branch != "no cur_branch " let cur_branch = a:cur_branch else let cur_branch = main_file endif if g:atp_debugRS > 1 silent echo "TIME0:" . reltimestr(reltime(time0)) endif let pattern = a:pattern let flags_supplied = substitute(flags_supplied, '[^bcenswWS]', '', 'g') " Add pattern to the search history if a:call_nr == 1 call histadd("search", a:pattern) let @/ = a:pattern endif " Set up searching flags let flag = flags_supplied if a:call_nr > 1 let flag = flags_supplied !~# 'c' ? flags_supplied . 'c' : flags_supplied endif let flag = substitute(flag, 'w', '', 'g') . 'W' let flag = flag !~# 'n' ? substitute(flag, 'n', '', 'g') . 'n' : flag let flag = substitute(flag, 's', '', 'g') if flags_supplied !~# 'b' " forward searching flag for input files: let flag_i = flags_supplied !~# 'c' ? flags_supplied . 'c' : flags_supplied else let flag_i = substitute(flags_supplied, 'c', '', 'g') endif let flag_i = flag_i !~# 'n' ? flag_i . 'n' : flag_i let flag_i = substitute(flag_i, 'w', '', 'g') . 'W' let flag_i = substitute(flag_i, 's', '', 'g') if g:atp_debugRS silent echo " flags_supplied:".flags_supplied." flag:".flag." flag_i:".flag_i." a:1=".(a:0 != 0 ? a:1 : "") endif " FIND PATTERN: let cur_pos = [line("."), col(".")] " We filter out the 's' flag which should be used only once " as the flags passed to next RecursiveSearch()es are based on flags_supplied variable " this will work. let s_flag = flags_supplied =~# 's' ? 1 : 0 let flags_supplied = substitute(flags_supplied, 's', '', 'g') if s_flag call setpos("''", getpos(".")) endif keepjumps let pat_pos = searchpos(pattern, flag) if g:atp_debugRS > 1 silent echo "TIME1:" . reltimestr(reltime(time0)) endif " FIND INPUT PATTERN: " (we do not need to search further than pat_pos) if pat_pos == [0, 0] let stop_line = flag !~# 'b' ? line("$") : 1 else let stop_line = pat_pos[0] endif keepjumps let input_pos = searchpos('\m^[^%]*\\input\s*{', flag_i . 'n', stop_line ) if g:atp_debugRS > 1 silent echo "TIME2:" . reltimestr(reltime(time0)) endif if g:atp_debugRS silent echo "Positions: ".string(cur_pos)." ".string(pat_pos)." ".string(input_pos)." in branch: ".cur_branch."#".expand("%:p") . " stop_line: " . stop_line endif " Down Accept: " the current value of down_accept let DOWN_ACCEPT = a:0 >= 2 ? a:2 : 0 " the value of down_accept in next turn let down_accept = getline(input_pos[0]) =~ pattern || input_pos == [0, 0] ? 1 : 0 " if g:atp_debugRS " silent echo "DOWN_ACCEPT=" . DOWN_ACCEPT . " down_accept=" . down_accept " endif " Decide what to do: accept the pattern, go to higher branch, go to lower " branch or say Pattern not found if flags_supplied !~# 'b' " FORWARD " cur < pat <= input if atplib#CompareCoordinates(cur_pos,pat_pos) && atplib#CompareCoordinates_leq(pat_pos, input_pos) let goto = 'ACCEPT' . 1 let goto_s = 'ACCEPT' " cur == pat <= input elseif cur_pos == pat_pos && atplib#CompareCoordinates_leq(pat_pos, input_pos) " this means that the 'flag' variable has to contain 'c' or the " wrapscan is on " ACCEPT if 'c' and wrapscan is off or there is another match below, " if there is not go UP. let wrapscan = ( flags_supplied =~# 'w' || &l:wrapscan && flags_supplied !~# 'W' ) if flag =~# 'c' let goto = 'ACCEPT' . 2 let goto_s = 'ACCEPT' elseif wrapscan " if in wrapscan and without 'c' flag let goto = 'UP' . 2 let goto_s = 'UP' else " this should not happen: cur == put can hold only in two cases: " wrapscan is on or 'c' is used. let goto = 'ERROR' . 2 let goto_s = 'ERROR' endif " pat < cur <= input elseif atplib#CompareCoordinates(pat_pos, cur_pos) && atplib#CompareCoordinates_leq(cur_pos, input_pos) let goto = 'UP' . 4 let goto_s = 'UP' " cur < input < pat elseif atplib#CompareCoordinates(cur_pos, input_pos) && atplib#CompareCoordinates(input_pos, pat_pos) let goto = 'UP' . 41 let goto_s = 'UP' " cur < input == pat /we are looking for '\\input'/ elseif atplib#CompareCoordinates(cur_pos, input_pos) && input_pos == pat_pos let goto = 'ACCEPT' let goto_s = 'ACCEPT' " input < cur <= pat (includes input = 0]) elseif atplib#CompareCoordinates(input_pos, cur_pos) && atplib#CompareCoordinates_leq(cur_pos, pat_pos) " cur == pat thus 'flag' contains 'c'. let goto = 'ACCEPT' let goto_s = 'ACCEPT' " cur == input elseif cur_pos == input_pos let goto = 'UP' let goto_s = 'UP' " cur < input < pat " input == 0 /there is no 'input' ahead - flag_i contains 'W'/ " /but there is no 'pattern ahead as well/ " at this stage: pat < cur (if not then input = 0 < cur <= pat was done above). elseif input_pos == [0, 0] if expand("%:p") == fnamemodify(main_file, ":p") " wrapscan if ( flags_supplied =~# 'w' || &l:wrapscan && flags_supplied !~# 'W' ) let new_flags = substitute(flags_supplied, 'w', '', 'g') . 'W' if a:wrap_nr <= 2 call cursor(1,1) if g:atp_debugRS silent echo " END 1 new_flags:" . new_flags redir END endif keepjumps call RecursiveSearch(main_file, a:start_file, "", tree_of_files, a:cur_branch, 1, a:wrap_nr+1, a:winsaveview, a:bufnr, a:strftime, vim_options, cwd, pattern, new_flags) return else let goto = "REJECT".1 let goto_s = "REJECT" " echohl ErrorMsg " echomsg 'Pattern not found: ' . a:pattern " echohl None endif else let goto = "REJECT".2 let goto_s = "REJECT" " echohl ErrorMsg " echomsg 'Pattern not found: ' . a:pattern " echohl None endif " if we are not in the main file go up. else let goto = "DOWN" . 21 let goto_s = "DOWN" endif else let goto = 'ERROR' . 13 let goto_s = 'ERROR' endif else " BACKWARD " input <= pat < cur (pat != 0) if atplib#CompareCoordinates(pat_pos, cur_pos) && atplib#CompareCoordinates_leq(input_pos, pat_pos) && pat_pos != [0, 0] " input < pat if input_pos != pat_pos let goto = 'ACCEPT' . 1 . 'b' let goto_s = 'ACCEPT' " input == pat else let goto = 'UP' . 1 . 'b' let goto_s = 'UP' endif " input <= pat == cur (input != 0) /pat == cur => pat != 0/ elseif cur_pos == pat_pos && atplib#CompareCoordinates_leq(input_pos, pat_pos) && input_pos != [0, 0] " this means that the 'flag' variable has to contain 'c' or the " wrapscan is on let wrapscan = ( flags_supplied =~# 'w' || &l:wrapscan && flags_supplied !~# 'W' ) if flag =~# 'c' let goto = 'ACCEPT' . 2 . 'b' let goto_s = 'ACCEPT' elseif wrapscan " if in wrapscan and without 'c' flag let goto = 'UP' . 2 . 'b' let goto_s = 'UP' else " this should not happen: cur == put can hold only in two cases: " wrapscan is on or 'c' is used. let goto = 'ERROR' . 2 . 'b' let goto_s = 'ERROR' endif " input <= cur < pat (input != 0) elseif atplib#CompareCoordinates(cur_pos, pat_pos) && atplib#CompareCoordinates_leq(input_pos, cur_pos) && input_pos != [0, 0] let goto = 'UP' . 4 .'b' let goto_s = 'UP' " pat < input <= cur (input != 0) elseif atplib#CompareCoordinates_leq(input_pos, cur_pos) && atplib#CompareCoordinates(pat_pos, input_pos) && input_pos != [0, 0] let goto = 'UP' . 41 . 'b' let goto_s = 'UP' " input == pat < cur (pat != 0) /we are looking for '\\input'/ elseif atplib#CompareCoordinates(input_pos, cur_pos) && input_pos == pat_pos && pat_pos != [0, 0] let goto = 'ACCEPT' . 5 . 'b' let goto_s = 'ACCEPT' " pat <= cur < input (pat != 0) elseif atplib#CompareCoordinates(cur_pos, input_pos) && atplib#CompareCoordinates_leq(pat_pos, cur_pos) && input_pos != [0, 0] " cur == pat thus 'flag' contains 'c'. let goto = 'ACCEPT' . 6 . 'b' let goto_s = 'ACCEPT' " cur == input elseif cur_pos == input_pos let goto = 'UP' let goto_s = 'UP' " input == 0 /there is no 'input' ahead - flag_i contains 'W'/ " /but there is no 'pattern ahead as well/ " at this stage: cur < pat || pat=input=0 (if not then pat <= cur was done above, input=pat=0 is the " only posibility to be passed by the above filter). elseif input_pos == [0, 0] " I claim that then cur < pat or pat=0 if expand("%:p") == fnamemodify(main_file, ":p") " wrapscan if ( flags_supplied =~# 'w' || &l:wrapscan && flags_supplied !~# 'W' ) let new_flags = substitute(flags_supplied, 'w', '', 'g') . 'W' if a:wrap_nr <= 2 call cursor(line("$"), col("$")) if g:atp_debugRS silent echo " END 2 new_flags:".new_flags redir END endif keepjumps call RecursiveSearch(main_file, a:start_file, "", tree_of_files, a:cur_branch, 1, a:wrap_nr+1, a:winsaveview, a:bufnr, a:strftime, vim_options, cwd, pattern, new_flags) if g:atp_debugRS > 1 silent echo "TIME_END:" . reltimestr(reltime(time0)) endif return else let goto = "REJECT" . 1 . 'b' let goto_s = "REJECT" " echohl ErrorMsg " echomsg 'Pattern not found: ' . a:pattern " echohl None endif else let goto = "REJECT" . 2 . 'b' let goto_s = "REJECT" endif " if we are not in the main file go up. else let goto = "DOWN" . 3 . 'b' let goto_s = "DOWN" " If using the following line DOWN_ACCEPT and down_accept " variables are not needed. This seems to be the best way. " There is no need to use this feature for " \input files. if pattern =~ '\\\\input' || pattern =~ '\\\\include' " if getline(input_pos[0]) =~ pattern || getline(".") =~ pattern let goto = "DOWN_ACCEPT" . 3 . 'b' let goto_s = "DOWN_ACCEPT" endif endif else let goto = 'ERROR' . 13 . 'b' let goto_s = 'ERROR' endif endif if g:atp_debugRS silent echo "goto:".goto endif if g:atp_debugRS >= 2 silent echo "TIME ***goto*** " . reltimestr(reltime(time0)) endif " When ACCEPTING the line: if goto_s == 'ACCEPT' keepjumps call setpos(".", [ 0, pat_pos[0], pat_pos[1], 0]) if flags_supplied =~# 'e' keepjumps call search(pattern, 'e', line(".")) endif "A Better solution must be found. " if &l:hlsearch " execute '2match Search /'.pattern.'/' " endif let time = matchstr(reltimestr(reltime(a:strftime)), '\d\+\.\d\d\d') . "sec." if a:wrap_nr == 2 && flags_supplied =~# 'b' redraw echohl WarningMsg echo "search hit TOP, continuing at BOTTOM " echohl Normal elseif a:wrap_nr == 2 redraw echohl WarningMsg echo "search hit BOTTOM, continuing at TOP " echohl Normal endif if g:atp_debugRS silent echo "FOUND PATTERN: " . a:pattern . " time " . time silent echo "" redir END endif " restore vim options if a:vim_options != { 'no_options' : 'no_options' } for option in keys(a:vim_options) execute "let &l:".option."=".a:vim_options[option] endfor endif exe "lcd " . fnameescape(cwd) " syntax enable filetype on filetype detect return " when going UP elseif goto_s == 'UP' call setpos(".", [ 0, input_pos[0], input_pos[0], 0]) " Open file and Search in it" " This should be done by kpsewhich: let file = matchstr(getline(input_pos[0]), '\\input\s*{\zs[^}]*\ze}') let file = atplib#append_ext(file, '.tex') let open = flags_supplied =~ 'b' ? 'keepalt edit + ' : 'keepalt edit +1 ' let swapfile = globpath(fnamemodify(file, ":h"), ( has("unix") ? "." : "" ) . fnamemodify(file, ":t") . ".swp") if !( a:call_nr == 1 && a:wrap_nr == 1 ) let open = "silent keepjumps " . open endif let projectVarDict = SaveProjectVariables() " let projectScript = SaveProjectVariables("g:atp_cached_local_variables") " let atp_ProjectScript = [ exists("g:atp_ProjectScript") ? g:atp_ProjectScript : b:atp_ProjectScript, exists("g:atp_ProjectScript") ] " let g:atp_ProjectScript = 0 if g:atp_debugRS >= 3 silent echo "projectVarDict : " . string(projectVarDict) let g:projectVarDict = projectVarDict elseif g:atp_debugRS >= 2 let g:projectVarDict = projectVarDict endif if g:atp_debugRS >= 2 silent echo "TIME ***goto UP before open*** " . reltimestr(reltime(time0)) endif " OPEN: if empty(swapfile) || bufexists(file) if g:atp_debugRS >= 2 silent echo "Alternate (before open) " . bufname("#") endif silent! execute open . fnameescape(file) else echoerr "Recursive Search: swap file: " . swapfile . " exists. Aborting." return endif if g:atp_debugRS >= 2 redir! >> /tmp/ATP_rs_debug silent echo "TIME ***goto UP after open*** " . reltimestr(reltime(time0)) endif " call RestoreProjectVariables(projectScript) " if atp_ProjectScript[1] " let g:atp_ProjectScript = atp_ProjectScript[0] " else " unlet g:atp_ProjectScript " endif call RestoreProjectVariables(projectVarDict) if g:atp_debugRS >= 2 silent echo "TIME ***goto UP restore variables *** " . reltimestr(reltime(time0)) endif if flags_supplied =~# 'b' call cursor(line("$"), col("$")) else call cursor(1,1) endif if g:atp_debugRS silent echo "In higher branch: " . file . " POS " line(".").":".col(".") silent echo "Open Command: '" . open . file . "'" silent echo "exist b:TreeOfFiles " . exists("b:TreeOfFiles") silent echo "flags_supplied: " . flags_supplied endif if g:atp_debugRS >= 2 silent echo "Alternate (after open) " . bufname("#") endif if g:atp_debugRS >= 2 silent echo "TIME_END: " . reltimestr(reltime(time0)) endif " let flag = flags_supplied =~ 'W' ? flags_supplied : flags_supplied . 'W' keepalt keepjumps call RecursiveSearch(main_file, a:start_file, "", tree_of_files, expand("%:p"), a:call_nr+1, a:wrap_nr, a:winsaveview, a:bufnr, a:strftime, vim_options, cwd, pattern, flags_supplied, down_accept) if g:atp_debugRS redir END endif return " when going DOWN elseif goto_s == 'DOWN' || goto_s == 'DOWN_ACCEPT' " We have to get the element in the tree one level up + line number let g:ATP_branch = "nobranch" let g:ATP_branch_line = "nobranch_line" if g:atp_debugRS silent echo " SearchInTree Args " . expand("%:p") endif if g:atp_RelativePath call SearchInTree(l:tree, main_file, atplib#RelativePath(expand("%:p"), resolve(b:atp_ProjectDir))) else call SearchInTree(l:tree, main_file, expand("%:p")) endif if g:atp_debugRS silent echo " SearchInTree found " . g:ATP_branch . " g:ATP_branch_line=" . g:ATP_branch_line endif if g:ATP_branch == "nobranch" echohl ErrorMsg echomsg "This probably happend while searching for \\input, it is not yet supported, if not it is a bug" echohl Normal silent! echomsg "Tree=" . string(l:tree) silent! echomsg "MainFile " . main_file . " current_file=" . expand("%:p") silent! echomsg "Going to file : " . g:ATP_branch . " ( g:ATP_branch ) " " restore the window and buffer! silent execute "keepjumps keepalt edit #" . a:bufnr call winrestview(a:winsaveview) return endif let next_branch = atplib#FullPath(g:ATP_branch) let swapfile = globpath(fnamemodify(next_branch, ":h"), ( has("unix") ? "." : "" ) . fnamemodify(next_branch, ":t") . ".swp") if a:call_nr == 1 && a:wrap_nr == 1 let open = 'silent keepalt edit +'.g:ATP_branch_line." ".fnameescape(next_branch) else let open = 'silent keepjumps keepalt edit +'.g:ATP_branch_line." ".fnameescape(next_branch) endif if g:atp_debugRS >= 2 silent echo "TIME ***goto DOWN before open*** " . reltimestr(reltime(time0)) endif let projectVarDict = SaveProjectVariables() " let projectScript = SaveProjectVariables("g:atp_cached_local_variables") " let atp_ProjectScript = [ exists("g:atp_ProjectScript") ? g:atp_ProjectScript : b:atp_ProjectScript, exists("g:atp_ProjectScript") ] " let g:atp_ProjectScript = 0 if empty(swapfile) || bufexists(next_branch) if g:atp_debugRS >= 2 silent echo "Alternate (before open) " . bufname("#") endif silent! execute open else echoerr "Recursive Search: swap file: " . swapfile . " exists. Aborting." return endif if g:atp_debugRS >= 2 silent echo "TIME ***goto DOWN after open*** " . reltimestr(reltime(time0)) endif " call RestoreProjectVariables(projectScript) " if atp_ProjectScript[1] " let g:atp_ProjectScript = atp_ProjectScript[0] " else " unlet g:atp_ProjectScript " endif call RestoreProjectVariables(projectVarDict) if g:atp_debugRS >= 2 silent echo "TIME ***goto DOWN restore project variables *** " . reltimestr(reltime(time0)) endif " call cursor(g:ATP_branch_line, 1) if flags_supplied !~# 'b' keepjumps call search('\m\\input\s*{[^}]*}', 'e', line(".")) endif if g:atp_debugRS silent echo "In lower branch: " . g:ATP_branch . " branch_line=" . g:ATP_branch_line. " POS " . line(".") . ":" . col(".") silent echo "Open Command '" . open . "'" silent echo "exist b:TreeOfFiles " . exists("b:TreeOfFiles") silent echo "flags_supplied: " . flags_supplied endif if g:atp_debugRS >= 2 silent echo "Alternate (after open) " . bufname("#") endif if g:atp_debugRS > 1 silent echo "TIME_END: " . reltimestr(reltime(time0)) endif unlet g:ATP_branch unlet g:ATP_branch_line " let flag = flags_supplied =~ 'W' ? flags_supplied : flags_supplied . 'W' if goto_s == 'DOWN' keepalt keepjumps call RecursiveSearch(main_file, a:start_file, "", tree_of_files, expand("%:p"), a:call_nr+1, a:wrap_nr, a:winsaveview, a:bufnr, a:strftime, vim_options, cwd, pattern, flags_supplied) endif " when REJECT elseif goto_s == 'REJECT' echohl ErrorMsg echomsg "Pattern not found" echohl Normal if g:atp_debugRS > 1 silent echo "TIME_END:" . reltimestr(reltime(time0)) endif " restore the window and buffer! " it is better to remember bufnumber silent execute "keepjumps keepalt edit #" . a:bufnr call winrestview(a:winsaveview) if g:atp_debugRS silent echo "" redir END endif " restore vim options if a:vim_options != { 'no_options' : 'no_options' } for option in keys(a:vim_options) execute "let &l:".option."=".a:vim_options[option] endfor endif exe "lcd " . fnameescape(cwd) " syntax enable filetype on filetype detect return " when ERROR elseif echohl ErrorMsg echomsg "This is a bug in ATP." echohl " restore vim options if a:vim_options != { 'no_options' : 'no_options' } for option in keys(a:vim_options) execute "let &l:".option."=".a:vim_options[option] endfor endif exe "lcd " . fnameescape(cwd) " syntax enable filetype on filetype detect " restore the window and buffer! silent execute "keepjumps keepalt edit #" . a:bufnr call winrestview(a:winsaveview) return endif endfunction catch /E127:/ endtry " }}} " User interface to s:RecursiveSearch function. " s:GetSearchArgs {{{ " This functionn returns arguments from - a list [ pattern, flag ] " It allows to pass arguments to s:Search in a similar way to :vimgrep, :ijump, ... function! s:GetSearchArgs(Arg,flags) if a:Arg =~ '^\/' let pattern = matchstr(a:Arg, '^\/\zs.*\ze\/') let flag = matchstr(a:Arg, '\/.*\/\s*\zs['.a:flags.']*\ze\s*$') elseif a:Arg =~ '^\i' && a:Arg !~ '^\w' let pattern = matchstr(a:Arg, '^\(\i\)\zs.*\ze\1') let flag = matchstr(a:Arg, '\(\i\).*\1\s*\zs['.a:flags.']*\ze\s*$') else let pattern = matchstr(a:Arg, '^\zs\S*\ze') let flag = matchstr(a:Arg, '^\S*\s*\zs['.a:flags.']*\ze\s*$') endif return [ pattern, flag ] endfunction "}}} " {{{ Search() try function! Search(Bang, Arg) let atp_MainFile = atplib#FullPath(b:atp_MainFile) let [ pattern, flag ] = s:GetSearchArgs(a:Arg, 'bceswW') " echomsg " pattern " . pattern . " flag " . flag if pattern == "" echohl ErrorMsg echomsg "Enclose the pattern with /.../" echohl Normal return endif if a:Bang == "!" || !exists("b:TreeOfFiles") call RecursiveSearch(atp_MainFile, expand("%:p"), 'make_tree', '', expand("%:p"), 1, 1, winsaveview(), bufnr("%"), reltime(), { 'no_options' : 'no_options' }, 'no_cwd', pattern, flag) else call RecursiveSearch(atp_MainFile, expand("%:p"), '', deepcopy(b:TreeOfFiles), expand("%:p"), 1, 1, winsaveview(), bufnr("%"), reltime(), { 'no_options' : 'no_options' }, 'no_cwd', pattern, flag) endif endfunction catch /E127: Cannot redefine function/ endtry " }}} function! ATP_ToggleNn(...) " {{{ let on = ( a:0 >=1 ? ( a:1 == 'on' ? 1 : 0 ) : !g:atp_mapNn ) let g:on = on if !on silent! nunmap n silent! nunmap N silent! aunmenu LaTeX.Toggle\ Nn\ [on] let g:atp_mapNn = 0 nmenu 550.79 &LaTeX.Toggle\ &Nn\ [off]:ToggleNn :ToggleNn imenu 550.79 &LaTeX.Toggle\ &Nn\ [off]:ToggleNn :ToggleNna tmenu LaTeX.Toggle\ Nn\ [off] atp maps to n,N. echomsg "vim nN maps" else silent! nmap n RecursiveSearchn silent! nmap N RecursiveSearchN silent! aunmenu LaTeX.Toggle\ Nn\ [off] let g:atp_mapNn = 1 nmenu 550.79 &LaTeX.Toggle\ &Nn\ [on]:ToggleNn :ToggleNn imenu 550.79 &LaTeX.Toggle\ &Nn\ [on]:ToggleNn :ToggleNna tmenu LaTeX.Toggle\ Nn\ [on] n,N vim normal commands. echomsg "atp nN maps" endif endfunction function! SearchHistCompletion(ArgLead, CmdLine, CursorPos) let search_history=[] let hist_entry = histget("search") let nr = 0 while hist_entry != "" call add(search_history, hist_entry) let nr -= 1 let hist_entry = histget("search", nr) endwhile return filter(search_history, "v:val =~# '^'.a:ArgLead") endfunction "}}} "}}} " These are only variables and front end functions for Bib Search Engine of ATP. " Search engine is define in autoload/atplib.vim script library. "{{{ BibSearch "-------------SEARCH IN BIBFILES ---------------------- " This function counts accurence of a:keyword in string a:line, " there are two methods keyword is a string to find (a:1=0)or a pattern to " match, the pattern used to is a:keyword\zs.* to find the place where to cut. " DEBUG: " command -buffer -nargs=* Count :echo atplib#count() let g:bibentries=['article', 'book', 'booklet', 'conference', 'inbook', 'incollection', 'inproceedings', 'manual', 'mastertheosis', 'misc', 'phdthesis', 'proceedings', 'techreport', 'unpublished'] "{{{ variables let g:bibmatchgroup ='String' let g:defaultbibflags = 'tabejsyu' let g:defaultallbibflags = 'tabejfsvnyPNSohiuHcp' let b:lastbibflags = g:defaultbibflags " Set the lastflags variable to the default value on the startup. let g:bibflagsdict=atplib#bibflagsdict " These two variables were s:... but I switched to atplib ... let g:bibflagslist = keys(g:bibflagsdict) let g:bibflagsstring = join(g:bibflagslist,'') let g:kwflagsdict={ '@a' : '@article', \ '@b' : '@book\%(let\)\@= 1 ? a:1 : "" " let flag = a:0 >= 2 ? a:2 : "" let Arg = ( a:0 >= 1 ? a:1 : "" ) if Arg != "" let [ pattern, flag ] = s:GetSearchArgs(Arg, 'aetbjsynvpPNShouH@BcpmMtTulL') else let [ pattern, flag ] = [ "", ""] endif let b:atp_LastBibPattern = pattern " This cannot be set here. It is set later by atplib#showresults function. " let b:atp_LastBibFlags = flag let @/ = pattern if g:atp_debugBS redir! >> /tmp/ATP_log silent! echo "==========BibSearch==========================" silent! echo "b:BibSearch_pattern=" . pattern silent! echo "b:BibSearch bang=" . a:bang silent! echo "b:BibSearch flag=" . flag let g:BibSearch_pattern = pattern let g:BibSearch_bang = a:bang let g:BibSearch_flag = flag redir END endif call atplib#showresults( atplib#searchbib(pattern, a:bang), flag, pattern) endfunction nnoremap BibSearchLast :call BibSearch("", b:atp_LastBibPattern, b:atp_LastBibFlags) " }}} "}}} endif "}}} " Commands And Highlightgs: " {{{ command! -buffer -bang -complete=customlist,SearchHistCompletion -nargs=* S :call Search(, ) | let v:searchforward = ( s:GetSearchArgs(, 'bceswW')[1] =~# 'b' ? 0 : 1 ) nmap RecursiveSearchn :call RecursiveSearch(atplib#FullPath(b:atp_MainFile), expand("%:p"), (exists("b:TreeOfFiles") ? "" : "make_tree"), (exists("b:TreeOfFiles") ? b:TreeOfFiles : {}), expand("%:p"), 1, 1, winsaveview(), bufnr("%"), reltime(), { 'no_options' : 'no_options' }, 'no_cwd', @/, v:searchforward ? "" : "b") nmap RecursiveSearchN :call RecursiveSearch(atplib#FullPath(b:atp_MainFile), expand("%:p"), (exists("b:TreeOfFiles") ? "" : "make_tree"), (exists("b:TreeOfFiles") ? b:TreeOfFiles : {}), expand("%:p"), 1, 1, winsaveview(), bufnr("%"), reltime(), { 'no_options' : 'no_options' }, 'no_cwd', @/, !v:searchforward ? "" : "b") if g:atp_mapNn " These two maps behaves now like n (N): after forward search n (N) acts as forward (backward), after " backward search n acts as backward (forward, respectively). nmap n RecursiveSearchn nmap N RecursiveSearchN " Note: the final step if the mapps n and N are made is in s:LoadHistory endif command! -buffer -bang LocalCommands :call LocalCommands("",) command! -buffer -bang -nargs=* DefiSearch :call DefiSearch(, ) command! -buffer -nargs=? -complete=customlist,atplib#OnOffComp ToggleNn :call ATP_ToggleNn() command! -buffer -bang -nargs=* BibSearch :call BibSearch(, ) " Hilighlting: hi link BibResultsFileNames Title hi link BibResultEntry ModeMsg hi link BibResultsMatch WarningMsg hi link BibResultsGeneral Normal hi link Chapter Normal hi link Section Normal hi link Subsection Normal hi link Subsubsection Normal hi link CurrentSection WarningMsg "}}} " vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1 ftplugin/ATP_files/various.vim [[[1 1920 " Author: Marcin Szamotulski " Descriptiion: These are various editting tools used in ATP. " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " Language: tex " Last Change: Sun Mar 20 04:00 2011 W let s:sourced = exists("s:sourced") ? 1 : 0 " FUNCTIONS: (source once) if !s:sourced || g:atp_reload_functions "{{{ " This is the wrap selection function. " {{{ WrapSelection function! s:WrapSelection(wrapper,...) let l:end_wrapper = ( a:0 >= 1 ? a:1 : '}' ) let l:cursor_pos = ( a:0 >= 2 ? a:2 : 'end' ) let l:new_line = ( a:0 >= 3 ? a:3 : 0 ) " let b:new_line=l:new_line " let b:cursor_pos=l:cursor_pos " let b:end_wrapper=l:end_wrapper let l:begin=getpos("'<") " todo: if and on 'Ä…' we should go one character further! (this is " a multibyte character) let l:end=getpos("'>") let l:pos_save=getpos(".") " hack for that: let l:pos=deepcopy(l:end) keepjumps call setpos(".",l:end) execute 'normal l' let l:pos_new=getpos(".") if l:pos_new[2]-l:pos[2] > 1 let l:end[2]+=l:pos_new[2]-l:pos[2]-1 endif let l:begin_line=getline(l:begin[1]) let l:end_line=getline(l:end[1]) let b:begin=l:begin[1] let b:end=l:end[1] " ToDo: this doesn't work yet! let l:add_indent=' ' if l:begin[1] != l:end[1] let l:bbegin_line=strpart(l:begin_line,0,l:begin[2]-1) let l:ebegin_line=strpart(l:begin_line,l:begin[2]-1) " DEBUG let b:bbegin_line=l:bbegin_line let b:ebegin_line=l:ebegin_line let l:bend_line=strpart(l:end_line,0,l:end[2]) let l:eend_line=strpart(l:end_line,l:end[2]) if l:new_line == 0 " inline " let b:debug=0 let l:begin_line=l:bbegin_line.a:wrapper.l:ebegin_line let l:end_line=l:bend_line.l:end_wrapper.l:eend_line call setline(l:begin[1],l:begin_line) call setline(l:end[1],l:end_line) let l:end[2]+=len(l:end_wrapper) else " let b:debug=1 " in seprate lines let l:indent=atplib#CopyIndentation(l:begin_line) if l:bbegin_line !~ '^\s*$' let l:begin_choice=1 call setline(l:begin[1],l:bbegin_line) call append(l:begin[1],l:indent.a:wrapper) " THERE IS AN ISSUE HERE! call append(copy(l:begin[1])+1,l:indent.substitute(l:ebegin_line,'^\s*','','')) let l:end[1]+=2 elseif l:bbegin_line =~ '^\s\+$' let l:begin_choice=2 call append(l:begin[1]-1,l:indent.a:wrapper) call append(l:begin[1],l:begin_line.l:ebegin_line) let l:end[1]+=2 else let l:begin_choice=3 call append(copy(l:begin[1])-1,l:indent.a:wrapper) let l:end[1]+=1 endif if l:eend_line !~ '^\s*$' let l:end_choice=4 call setline(l:end[1],l:bend_line) call append(l:end[1],l:indent.l:end_wrapper) call append(copy(l:end[1])+1,l:indent.substitute(l:eend_line,'^\s*','','')) else let l:end_choice=5 call append(l:end[1],l:indent.l:end_wrapper) endif if (l:end[1] - l:begin[1]) >= 0 if l:begin_choice == 1 let i=2 elseif l:begin_choice == 2 let i=2 elseif l:begin_choice == 3 let i=1 endif if l:end_choice == 5 let j=l:end[1]-l:begin[1]+1 else let j=l:end[1]-l:begin[1]+1 endif while i < j " Adding indentation doesn't work in this simple way here? " but the result is ok. call setline(l:begin[1]+i,l:indent.l:add_indent.getline(l:begin[1]+i)) let i+=1 endwhile endif let l:end[1]+=2 let l:end[2]=1 endif else let l:begin_l=strpart(l:begin_line,0,l:begin[2]-1) let l:middle_l=strpart(l:begin_line,l:begin[2]-1,l:end[2]-l:begin[2]+1) let l:end_l=strpart(l:begin_line,l:end[2]) if l:new_line == 0 " inline let l:line=l:begin_l.a:wrapper.l:middle_l.l:end_wrapper.l:end_l call setline(l:begin[1],l:line) let l:end[2]+=len(a:wrapper)+1 else " in seprate lines let b:begin_l=l:begin_l let b:middle_l=l:middle_l let b:end_l=l:end_l let l:indent=atplib#CopyIndentation(l:begin_line) if l:begin_l =~ '\S' call setline(l:begin[1],l:begin_l) call append(copy(l:begin[1]),l:indent.a:wrapper) call append(copy(l:begin[1])+1,l:indent.l:add_indent.l:middle_l) call append(copy(l:begin[1])+2,l:indent.l:end_wrapper) if substitute(l:end_l,'^\s*','','') =~ '\S' call append(copy(l:begin[1])+3,l:indent.substitute(l:end_l,'^\s*','','')) endif else call setline(copy(l:begin[1]),l:indent.a:wrapper) call append(copy(l:begin[1]),l:indent.l:add_indent.l:middle_l) call append(copy(l:begin[1])+1,l:indent.l:end_wrapper) if substitute(l:end_l,'^\s*','','') =~ '\S' call append(copy(l:begin[1])+2,l:indent.substitute(l:end_l,'^\s*','','')) endif endif endif endif if l:cursor_pos == "end" let l:end[2]+=len(l:end_wrapper)-1 call setpos(".",l:end) elseif l:cursor_pos =~ '\d\+' let l:pos=l:begin let l:pos[2]+=l:cursor_pos call setpos(".",l:pos) elseif l:cursor_pos == "current" keepjumps call setpos(".",l:pos_save) elseif l:cursor_pos == "begin" let l:begin[2]+=len(a:wrapper)-1 keepjumps call setpos(".",l:begin) endif endfunction "}}} "{{{ Inteligent Wrap Selection " This function selects the correct font wrapper for math/text environment. " the rest of arguments are the same as for WrapSelection (and are passed to " WrapSelection function) " a:text_wrapper = [ 'begin_text_wrapper', 'end_text_wrapper' ] " a:math_wrapper = [ 'begin_math_wrapper', 'end_math_wrapper' ] " if end_(math\|text)_wrapper is not given '}' is used (but neverthe less both " arguments must be lists). function! s:InteligentWrapSelection(text_wrapper, math_wrapper, ...) let cursor_pos = ( a:0 >= 1 ? a:2 : 'end' ) let new_line = ( a:0 >= 2 ? a:3 : 0 ) let MathZones = copy(g:atp_MathZones) let pattern = '^texMathZone[VWX]' if b:atp_TexFlavor == 'plaintex' call add(MathZones, 'texMathZoneY') let pattern = '^texMathZone[VWXY]' endif " select the correct wrapper let MathZone = get(filter(map(synstack(line("."),max([1,col(".")-1])),"synIDattr(v:val,'name')"),"v:val=~pattern"),0,"") if MathZone =~ '^texMathZone[VWY]' let step = 2 elseif MathZone == 'texMathZoneX' let step = 1 else let step = 0 endif " Note: in visual mode col(".") returns always the column starting position of " the visual area, thus it is enough to check the begining (if we stand on " $:\(:\[:$$ use text wrapper). if !empty(MathZone) && col(".") > step && atplib#CheckSyntaxGroups(MathZones, line("."), max([1, col(".")-step])) let begin_wrapper = a:math_wrapper[0] let end_wrapper = get(a:math_wrapper,1, '}') else let begin_wrapper = a:text_wrapper[0] let end_wrapper = get(a:text_wrapper,1, '}') endif " if the wrapper is empty return " useful for wrappers which are valid only in one mode. if begin_wrapper == "" return endif call s:WrapSelection(begin_wrapper, end_wrapper, cursor_pos, new_line) endfunction "}}} " Inteligent Aling " TexAlign {{{ " This needs Aling vim plugin. function! TexAlign() let save_pos = getpos(".") let synstack = map(synstack(line("."), col(".")), 'synIDattr( v:val, "name")') let balign=searchpair('\\begin\s*{\s*array\s*}', '', '\\end\s*{\s*array\s*}', 'bnW') let [bmatrix, bmatrix_col]=searchpairpos('\\matrix\s*\[[^]]*\]\s*\zs{', '', '}', 'bnW', '', max([1, (line(".")-g:atp_completion_limits[2])])) if bmatrix let bpat = '\\matrix\s*\[[^]]*\]\s*{' let bline = bmatrix+1 let epat = '}' let AlignCtr = 'jl+ &' let env = "matrix" elseif balign let bpat = '\\begin\s*{\s*array\s*}' let bline = balign+1 let epat = '\\end\s*{\s*array\s*}' let AlignCtr = 'Il+ &' let env = "array" elseif count(synstack, 'texMathZoneA') || count(synstack, 'texMathZoneAS') let bpat = '\\begin\s*{\s*align\*\=\s*}' let epat = '\\end\s*{\s*align\*\=\s*}' let AlignCtr = 'Il+ &' let env = "align" elseif count(synstack, 'texMathZoneB') || count(synstack, 'texMathZoneBS') let bpat = '\\begin\s*{\s*alignat\*\=\s*}' let epat = '\\end\s*{\s*alignat\*\=\s*}' let AlignCtr = 'Il+ &' let env = "alignat" elseif count(synstack, 'texMathZoneD') || count(synstack, 'texMathZoneDS') let bpat = '\\begin\s*{\s*eqnarray\*\=\s*}' let epat = '\\end\s*{\s*eqnarray\*\=\s*}' let AlignCtr = 'Il+ &' let env = "eqnarray" elseif count(synstack, 'texMathZoneE') || count(synstack, 'texMathZoneES') let bpat = '\\begin\s*{\s*equation\*\=\s*}' let epat = '\\end\s*{\s*equation\*\=\s*}' let AlignCtr = 'Il+ =+-' let env = "equation" elseif count(synstack, 'texMathZoneF') || count(synstack, 'texMathZoneFS') let bpat = '\\begin\s*{\s*flalign\*\=\s*}' let epat = '\\end\s*{\s*flalign\*\=\s*}' let AlignCtr = 'jl+ &' let env = "falign" " elseif count(synstack, 'texMathZoneG') || count(synstack, 'texMathZoneGS') " gather doesn't need alignment (by design it give unaligned equation. " let bpat = '\\begin\s*{\s*gather\*\=\s*}' " let epat = '\\end\s*{\s*gather\*\=\s*}' " let AlignCtr = 'Il+ &' " let env = "gather" elseif count(synstack, 'displaymath') let bpat = '\\begin\s*{\s*displaymath\*\=\s*}' let epat = '\\end\s*{\s*displaymath\*\=\s*}' let AlignCtr = 'Il+ =+-' let env = "displaymath" elseif searchpair('\\begin\s*{\s*tabular\s*\}', '', '\\end\s*{\s*tabular\s*}', 'bnW', '', max([1, (line(".")-g:atp_completion_limits[2])])) let bpat = '\\begin\s*{\s*tabular\*\=\s*}' let epat = '\\end\s*{\s*tabular\*\=\s*}' let AlignCtr = 'jl+ &' let env = "tabular" else return endif " let g:env=env if !exists("bline") let bline = search(bpat, 'cnb') + 1 endif if env != "matrix" let eline = searchpair(bpat, '', epat, 'cn') - 1 else let saved_pos = getpos(".") call cursor(bmatrix, bmatrix_col) let eline = searchpair('{', '', '}', 'n') - 1 call cursor(saved_pos[1], saved_pos[2]) endif " let g:bline = bline " let g:eline = eline if bline <= eline execute bline . ',' . eline . 'Align ' . AlignCtr endif call setpos(".", save_pos) endfunction "}}} " Insert() function, which is used to insert text depending on mode: text/math. " {{{ Insert() " Should be called via an imap: " imap :call Insert(text, math)a " a:text = text to insert in text mode " a:math = text to insert in math mode function! Insert(text, math) let MathZones = copy(g:atp_MathZones) if b:atp_TexFlavor == 'plaintex' call add(MathZones, 'texMathZoneY') endif " select the correct wrapper if atplib#CheckSyntaxGroups(MathZones, line("."), col(".")) let insert = a:math else let insert = a:text endif " if the insert variable is empty return if empty(insert) return endif let line = getline(".") let col = col(".") let new_line = strpart(line, 0, col) . insert . strpart(line, col) call setline(line("."), new_line) call cursor(line("."), col(".")+len(insert)) return "" endfunction " }}} " Insert \item update the number. " {{{ InsertItem() " ToDo: indent function! InsertItem() let begin_line = searchpair( '\\begin\s*{\s*\%(enumerate\|itemize\)\s*}', '', '\\end\s*{\s*\%(enumerate\|itemize\)\s*}', 'bnW') let saved_pos = getpos(".") call cursor(line("."), 1) " This will work with \item [[1]], but not with \item [1]] let [ bline, bcol] = searchpos('\\item\s*\zs\[', 'b', begin_line) if bline == 0 keepjumps call setpos(".", saved_pos) if search('\\item\>', 'nb', begin_line) let new_line = strpart(getline("."), 0, col(".")) . '\item '. strpart(getline("."), col(".")) else let new_line = strpart(getline("."), 0, col(".")) . '\item'. strpart(getline("."), col(".")) endif call setline(line("."), new_line) " Indent the line: if &l:indentexpr != "" execute "let indent = " . &l:indentexpr let i = 1 let ind = "" while i <= indent let ind .= " " let i += 1 endwhile else indent = -1 ind = matchstr(getline("."), '^\s*') endif call setline(line("."), ind . substitute(getline("."), '^\s*', '', '')) " Set the cursor position let saved_pos[2] += len('\item') + indent keepjumps call setpos(".", saved_pos) return "" endif let [ eline, ecol] = searchpairpos('\[', '', '\]', 'nr', '', line(".")) if eline != bline return "" endif let item = strpart(getline("."), bcol, ecol - bcol - 1) let bpat = '(\|{\|\[' let epat = ')\|}\|\]\|\.' let number = matchstr(item, '\d\+') let subNr = matchstr(item, '\d\+\zs\a\ze') let space = matchstr(getline("."), '\\item\zs\s*\ze\[') if nr2char(number) != "" && subNr == "" let new_item = substitute(item, number, number + 1, '') elseif item =~ '\%('.bpat.'\)\=\s*\%(i\|ii\|iii\|iv\|v\|vi\|vii\|viii\|ix\)\%('.epat.'\)\=$' let numbers = [ 'i', 'ii', 'iii', 'iv', 'v', 'vi', 'vii', 'viii', 'ix', 'x' ] let roman = matchstr(item, '\%('.bpat.'\)\=\s*\zs\w\+\ze\s*\%('.epat.'\)\=$') let new_roman = get(numbers, index(numbers, roman) + 1, 'xi') let new_item = substitute(item, '^\%('.bpat.'\)\=\s*\zs\a\+\ze\s*\%('.epat.'\)\=$', new_roman, 'g') elseif nr2char(number) != "" && subNr != "" let alphabet = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'w', 'x', 'y', 'z' ] let char = matchstr(item, '^\%('.bpat.'\)\=\s*\d\+\zs\a\ze\s*\%('.epat.'\)\=$') let new_char = get(alphabet, index(alphabet, char) + 1, 'z') let new_item = substitute(item, '^\%('.bpat.'\)\=\s*\d\+\zs\a\ze\s*\%('.epat.'\)\=$', new_char, 'g') elseif item =~ '\%('.bpat.'\)\=\s*\w\s*\%('.epat.'\)\=' let alphabet = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'w', 'x', 'y', 'z' ] let char = matchstr(item, '^\%('.bpat.'\)\=\s*\zs\w\ze\s*\%('.epat.'\)\=$') let new_char = get(alphabet, index(alphabet, char) + 1, 'a') let new_item = substitute(item, '^\%('.bpat.'\)\=\s*\zs\w\ze\s*\%('.epat.'\)\=$', new_char, 'g') else let new_item = item endif keepjumps call setpos(".", saved_pos) let new_line = strpart(getline("."), 0, col(".")) . '\item' . space . '[' . new_item . '] ' . strpart(getline("."), col(".")) call setline(line("."), new_line) " Indent the line: if &l:indentexpr != "" execute "let indent = " . &l:indentexpr let i = 1 let ind = "" while i <= indent let ind .= " " let i += 1 endwhile else ind = matchstr(getline("."), '^\s*') endif call setline(line("."), ind . substitute(getline("."), '^\s*', '', '')) " Set the cursor position let saved_pos[2] += len('\item' . space . '[' . new_item . ']') + indent keepjumps call setpos(".", saved_pos) return "" endfunction " }}} " Editing Toggle Functions "{{{ Variables if !exists("g:atp_no_toggle_environments") let g:atp_no_toggle_environments=[ 'document', 'tikzpicture', 'picture'] endif if !exists("g:atp_toggle_environment_1") let g:atp_toggle_environment_1=[ 'center', 'flushleft', 'flushright', 'minipage' ] endif if !exists("g:atp_toggle_environment_2") let g:atp_toggle_environment_2=[ 'enumerate', 'itemize', 'list', 'description' ] endif if !exists("g:atp_toggle_environment_3") let g:atp_toggle_environment_3=[ 'quotation', 'quote', 'verse' ] endif if !exists("g:atp_toggle_environment_4") let g:atp_toggle_environment_4=[ 'theorem', 'proposition', 'lemma' ] endif if !exists("g:atp_toggle_environment_5") let g:atp_toggle_environment_5=[ 'corollary', 'remark', 'note' ] endif if !exists("g:atp_toggle_environment_6") let g:atp_toggle_environment_6=[ 'equation', 'align', 'array', 'alignat', 'gather', 'flalign', 'multline' ] endif if !exists("g:atp_toggle_environment_7") let g:atp_toggle_environment_7=[ 'smallmatrix', 'pmatrix', 'bmatrix', 'Bmatrix', 'vmatrix' ] endif if !exists("g:atp_toggle_environment_8") let g:atp_toggle_environment_8=[ 'tabbing', 'tabular'] endif if !exists("g:atp_toggle_labels") let g:atp_toggle_labels=1 endif "}}} "{{{ ToggleStar " this function adds a star to the current environment " todo: to doc. function! s:ToggleStar() " limit: let from_line=max([1,line(".")-g:atp_completion_limits[2]]) let to_line=line(".")+g:atp_completion_limits[2] " omit pattern let no_star=copy(g:atp_no_star_environments) let cond = atplib#SearchPackage('mdwlist') if cond || exists("b:atp_LocalEnvironments") && index(b:atp_LocalEnvironments, 'enumerate*') != -1 call remove(no_star, index(no_star, 'enumerate')) endif if cond || exists("b:atp_LocalEnvironments") && index(b:atp_LocalEnvironments, 'itemize') != -1 call remove(no_star, index(no_star, 'itemize')) endif if cond || exists("b:atp_LocalEnvironments") && index(b:atp_LocalEnvironments, 'description') != -1 call remove(no_star, index(no_star, 'description')) endif let omit=join(no_star,'\|') let open_pos=searchpairpos('\\begin\s*{','','\\end\s*{[^}]*}\zs','cbnW','getline(".") =~ "\\\\begin\\s*{".omit."}"',from_line) let env_name=matchstr(strpart(getline(open_pos[0]),open_pos[1]),'begin\s*{\zs[^}]*\ze}') if ( open_pos == [0, 0] || index(no_star, env_name) != -1 ) && getline(line(".")) !~ '\\\%(part\|chapter\|\%(sub\)\{0,2}section\)' return endif if env_name =~ '\*$' let env_name=substitute(env_name,'\*$','','') let close_pos=searchpairpos('\\begin\s*{'.env_name.'\*}','','\\end\s*{'.env_name.'\*}\zs','cnW',"",to_line) if close_pos != [0, 0] call setline(open_pos[0],substitute(getline(open_pos[0]),'\(\\begin\s*{\)'.env_name.'\*}','\1'.env_name.'}','')) call setline(close_pos[0],substitute(getline(close_pos[0]), \ '\(\\end\s*{\)'.env_name.'\*}','\1'.env_name.'}','')) echomsg "Star removed from '".env_name."*' at lines: " .open_pos[0]." and ".close_pos[0] endif else let close_pos=searchpairpos('\\begin\s{'.env_name.'}','','\\end\s*{'.env_name.'}\zs','cnW',"",to_line) if close_pos != [0, 0] call setline(open_pos[0],substitute(getline(open_pos[0]), \ '\(\\begin\s*{\)'.env_name.'}','\1'.env_name.'\*}','')) call setline(close_pos[0],substitute(getline(close_pos[0]), \ '\(\\end\s*{\)'.env_name.'}','\1'.env_name.'\*}','')) echomsg "Star added to '".env_name."' at lines: " .open_pos[0]." and ".close_pos[0] endif endif " Toggle the * in \section, \chapter, \part commands. if getline(line(".")) =~ '\\\%(part\|chapter\|\%(sub\)\{0,2}section\)\*' let pos = getpos(".") substitute/\(\\part\|\\chapter\|\\\%(sub\)\{0,2}section\)\*/\1/ call cursor(pos[1], pos[2]) elseif getline(line(".")) =~ '\\\%(part\|chapter\|\%(sub\)\{0,2}section\)' let pos = getpos(".") substitute/\(\\part\|\\chapter\|\\\%(sub\)\{0,2}section\)/\1*/ call cursor(pos[1], pos[2]) endif endfunction "}}} "{{{ ToggleEnvironment " this function toggles envrionment name. " Todo: to doc. " a:ask = 0 toggle, 1 ask for the new env name if not given as the first argument. " the argument specifies the speed (if -1 then toggle back) " default is '1' or the new environment name try function! s:ToggleEnvironment(ask, ...) let atp_MainFile = atplib#FullPath(b:atp_MainFile) " l:add might be a number or an environment name " if it is a number the function will jump this amount in appropriate list " (g:atp_toggle_environment_[123...]) to find new environment name let l:add = ( a:0 >= 1 ? a:1 : 1 ) " limit: let l:from_line=max([1,line(".")-g:atp_completion_limits[2]]) let l:to_line=line(".")+g:atp_completion_limits[2] " omit pattern let l:omit=join(g:atp_no_toggle_environments,'\|') let l:open_pos=searchpairpos('\\begin\s*{','','\\end\s*{[^}]*}\zs','bnW','getline(".") =~ "\\\\begin\\s*{".l:omit."}"',l:from_line) let l:env_name=matchstr(strpart(getline(l:open_pos[0]),l:open_pos[1]),'begin\s*{\zs[^}]*\ze}') let l:label=matchstr(strpart(getline(l:open_pos[0]),l:open_pos[1]),'\\label\s*{\zs[^}]*\ze}') " DEBUG " let b:line=strpart(getline(l:open_pos[0]),l:open_pos[1]) " let b:label=l:label " let b:env_name=l:env_name if l:open_pos == [0, 0] || index(g:atp_no_toggle_environments,l:env_name) != -1 return endif let l:env_name_ws=substitute(l:env_name,'\*$','','') if !a:ask let l:variable="g:atp_toggle_environment_1" let l:i=1 while 1 let l:env_idx=index({l:variable},l:env_name_ws) if l:env_idx != -1 break else let l:i+=1 let l:variable="g:atp_toggle_environment_".l:i endif if !exists(l:variable) return endif endwhile if l:add > 0 && l:env_idx > len({l:variable})-l:add-1 let l:env_idx=0 elseif ( l:add < 0 && l:env_idx < -1*l:add ) let l:env_idx=len({l:variable})-1 else let l:env_idx+=l:add endif let l:new_env_name={l:variable}[l:env_idx] if l:env_name =~ '\*$' let l:new_env_name.="*" endif else if l:add == 1 let l:new_env_name=input("What is the new name for " . l:env_name . "? type and hit ", "", "customlist,EnvCompletion" ) if l:new_env_name == "" echomsg "Environment name not changed" return endif else let l:new_env_name = l:add endif endif " DEBUG " let g:i=l:i " let g:env_idx=l:env_idx " let g:env_name=l:env_name " let g:add = l:add " let g:new_env_name=l:new_env_name let l:env_name=escape(l:env_name,'*') let l:close_pos=searchpairpos('\\begin\s*{'.l:env_name.'}','','\\end\s*{'.l:env_name.'}\zs','nW',"",l:to_line) if l:close_pos != [0, 0] call setline(l:open_pos[0],substitute(getline(l:open_pos[0]),'\(\\begin\s*{\)'.l:env_name.'}','\1'.l:new_env_name.'}','')) call setline(l:close_pos[0],substitute(getline(l:close_pos[0]), \ '\(\\end\s*{\)'.l:env_name.'}','\1'.l:new_env_name.'}','')) echomsg "Environment toggeled at lines: " .l:open_pos[0]." and ".l:close_pos[0] endif if l:label != "" && g:atp_toggle_labels if l:env_name == "" let l:new_env_name_ws=substitute(l:new_env_name,'\*$','','') let l:new_short_name=get(g:atp_shortname_dict,l:new_env_name_ws,"") let l:new_label = l:new_short_name . strpart(l:label, stridx(l:label, g:atp_separator)) " let g:new_label = l:new_label . "XXX" else " let g:label = l:label let l:new_env_name_ws=substitute(l:new_env_name,'\*$','','') " let g:new_env_name_ws=l:new_env_name_ws let l:new_short_name=get(g:atp_shortname_dict,l:new_env_name_ws,"") " let g:new_short_name=l:new_short_name let l:short_pattern= '^\(\ze:\|' . join(values(filter(g:atp_shortname_dict,'v:val != ""')),'\|') . '\)' " let g:short_pattern=l:short_pattern let l:short_name=matchstr(l:label, l:short_pattern) " let g:short_name=l:short_name let l:new_label=substitute(l:label,'^'.l:short_name,l:new_short_name,'') " let g:new_label=l:new_label endif " check if new label is in use! let pos_save=getpos(".") let n=search('\m\C\\\(label\|\%(eq\|page\)\?ref\)\s*{'.l:new_label.'}','nwc') if n == 0 && l:new_label != l:label let hidden = &hidden set hidden silent! keepjumps execute l:open_pos[0].'substitute /\\label{'.l:label.'}/\\label{'.l:new_label.'}' " This should be done for every file in the project. if !exists("b:TypeDict") call TreeOfFiles(atp_MainFile) endif let save_view = winsaveview() let file = expand("%:p") let project_files = keys(filter(b:TypeDict, "v:val == 'input'")) + [ atp_MainFile ] for project_file in project_files if atplib#FullPath(project_file) != expand("%:p") exe "silent keepalt edit " . project_file endif let pos_save_pf=getpos(".") silent! keepjumps execute '%substitute /\\\(eq\|page\)\?\(ref\s*\){'.l:label.'}/\\\1\2{'.l:new_label.'}/gIe' keepjumps call setpos(".", pos_save_pf) endfor execute "keepalt buffer " . file keepjumps call setpos(".", pos_save) let &hidden = hidden elseif n != 0 && l:new_label != l:label echohl WarningMsg echomsg "Labels not changed, new label: ".l:new_label." is in use!" echohl Normal endif endif return l:open_pos[0]."-".l:close_pos[0] endfunction catch /E127:/ endtry "}}} " This is completion for input() inside ToggleEnvironment which uses " b:atp_LocalEnvironments variable. function! EnvCompletion(ArgLead, CmdLine, CursorPos) if !exists("b:atp_LocalEnvironments") LocalCommands endif let env_list = copy(b:atp_LocalEnvironments) " add standard and ams environment if not present. let env_list=atplib#Extend(env_list, g:atp_Environments) if atplib#SearchPackage('amsmath') let env_list=atplib#Extend(env_list, g:atp_amsmath_environments) endif call filter(env_list, "v:val =~ '^' .a:ArgLead") return env_list endfunction " TexDoc commanand and its completion " {{{ TexDoc " This is non interactive !, use :!texdoc for interactive command. " But it simulates it with a nice command completion (Ctrl-D, ) " based on alias files for texdoc. function! s:TexDoc(...) let texdoc_arg = "" for i in range(1,a:0) let texdoc_arg.=" " . a:{i} endfor if texdoc_arg == "" let texdoc_arg = g:atp_TeXdocDefault endif " If the file is a text file texdoc is 'cat'-ing it into the terminal, " we use echo to capture the output. " The rediraction prevents showing texdoc info messages which are not that " important, if a document is not found texdoc sends a message to the standard " output not the error. " " -I prevents from using interactive menus echo system("texdoc " . texdoc_arg . " 2>/dev/null") endfunction function! s:TeXdoc_complete(ArgLead, CmdLine, CursorPos) let texdoc_alias_files=split(system("texdoc -f"), '\n') call filter(texdoc_alias_files, "v:val =~ 'active'") call map(texdoc_alias_files, "substitute(substitute(v:val, '^[^/]*\\ze', '', ''), '\/\/\\+', '/', 'g')") let aliases = [] for file in texdoc_alias_files call extend(aliases, readfile(file)) endfor call filter(aliases, "v:val =~ 'alias'") call filter(map(aliases, "matchstr(v:val, '^\\s*alias\\s*\\zs\\S*\\ze\\s*=')"),"v:val !~ '^\\s*$'") if exists("g:atp_latexpackages") call extend(aliases, g:atp_latexpackages) endif return filter(copy(aliases), "v:val =~ '^' . a:ArgLead") endfunction " }}} " This function deletes tex specific output files (exept the pdf/dvi file, unless " bang is used - then also delets the current output file) " {{{ Delete function! s:Delete(delete_output) let atp_MainFile = atplib#FullPath(b:atp_MainFile) call atplib#outdir() let atp_tex_extensions=deepcopy(g:atp_tex_extensions) if a:delete_output == "!" if b:atp_TexCompiler == "pdftex" || b:atp_TexCompiler == "pdflatex" let ext="pdf" else let ext="dvi" endif call add(atp_tex_extensions,ext) endif for ext in atp_tex_extensions if executable(g:rmcommand) if g:rmcommand =~ "^\s*rm\p*" || g:rmcommand =~ "^\s*perltrash\p*" if ext != "dvi" && ext != "pdf" let rm=g:rmcommand . " " . shellescape(b:atp_OutDir) . "*." . ext . " 2>/dev/null && echo Removed: ./*" . ext else let rm=g:rmcommand . " " . shellescape(fnamemodify(atp_MainFile,":r")).".".ext . " 2>/dev/null && echo Removed: " . fnamemodify(atp_MainFile,":r").".".ext endif endif echo system(rm) else let file=b:atp_OutDir . fnamemodify(expand("%"),":t:r") . "." . ext if delete(file) == 0 echo "Removed " . file endif endif endfor endfunction "}}} "{{{ OpenLog, TexLog, TexLog Buffer Options, PdfFonts, YesNoCompletion "{{{ s:Search function for Log Buffer function! Search(pattern, flag, ...) echo "" let center = ( a:0 >= 1 ? a:1 : 1 ) let @/ = a:pattern " Count: " let nr = 1 " while nr <= a:count " let keepjumps = ( a:nr < a:count ? 'keepjumps' : '') " exe keepjumps . "let line = search(a:pattern, a:flag)" " let nr += 1 " endwhile let line = search(a:pattern, a:flag) if !line let message = a:flag =~# 'b' ? 'previous' : 'next' if a:pattern =~ 'warning' let type = 'warning' elseif a:pattern =~ '\^!' let type = 'error' elseif a:pattern =~ 'info' let type = 'info' else let type = '' endif echohl WarningMsg echo "No " . message . " " . type . " message." echohl Normal endif " This fails (?): " if center " normal zz " endif endfunction " command! -count=1 -nargs=* Search :call Search(,) function! Searchpair(start, middle, end, flag, ...) let center = ( a:0 >= 1 ? a:1 : 1 ) if getline(".")[col(".")-1] == ')' let flag= a:flag.'b' else let flag= substitute(a:flag, 'b', '', 'g') endif call searchpair(a:start, a:middle, a:end, flag) " if center " normal zz " endif endfunction "}}} function! s:OpenLog() if filereadable(&l:errorfile) let projectVarDict = SaveProjectVariables() let g:projectVarDict = projectVarDict let s:winnr = bufwinnr("") exe "rightbelow split +setl\\ nospell\\ ruler\\ syn=log_atp\\ autoread " . fnameescape(&l:errorfile) call RestoreProjectVariables(projectVarDict) map q :bd! nnoremap ]m :call Search('\CWarning\\|^!', 'W') nnoremap [m :call Search('\CWarning\\|^!', 'bW') nnoremap ]w :call Search('\CWarning', 'W') nnoremap [w :call Search('\CWarning', 'bW') nnoremap ]c :call Search('\CLaTeX Warning: Citation', 'W') nnoremap [c :call Search('\CLaTeX Warning: Citation', 'bW') nnoremap ]r :call Search('\CLaTeX Warning: Reference', 'W') nnoremap [r :call Search('\CLaTeX Warning: Reference', 'bW') nnoremap ]e :call Search('^!', 'W') nnoremap [e :call Search('^!', 'bW') nnoremap ]f :call Search('\CFont \%(Info\\|Warning\)', 'W') nnoremap [f :call Search('\CFont \%(Info\\|Warning\)', 'bW') nnoremap ]p :call Search('\CPackage', 'W') nnoremap [p :call Search('\CPackage', 'bW') nnoremap ]P :call Search('\[\_d\+\zs', 'W') nnoremap [P :call Search('\[\_d\+\zs', 'bW') nnoremap ]i :call Search('\CInfo', 'W') nnoremap [i :call Search('\CInfo', 'bW') nnoremap % :call Searchpair('(', '', ')', 'W') " This prevents vim from reloading with 'autoread' option: the buffer is " modified outside and inside vim. try silent! execute 'keepjumps %g/^\s*$/d' silent! execute "keepjumps normal ''" catch /E486:/ endtry function! SyncTex(bang,...) let cwd = getcwd() exe "lcd " . fnameescape(b:atp_ProjectDir ) let g:debugST = 0 " if sync = 1 sync log file and the window - can be used by autocommand let sync = ( a:0 >= 1 ? a:1 : 0 ) if g:atp_debugST let g:sync = sync endif if sync && !g:atp_LogSync exe "normal! " . cwd let g:debugST = 1 return endif " Find the end pos of error msg keepjumps let [ stopline, stopcol ] = searchpairpos('(', '', ')', 'nW') if g:atp_debugST let g:stopline = stopline endif let saved_pos = getpos(".") " Be linewise call setpos(".", [0, line("."), 1, 0]) " Find the line nr " keepjumps let [ LineNr, ColNr ] = searchpos('^l.\zs\d\+\>\|oninput line \zs\|at lines \zs', 'W', stopline) keepjumps let [ LineNr, ColNr ] = searchpos('^l.\zs\d\+\>\|o\n\=n\_s\+i\n\=n\n\=p\n\=u\n\=t\_s\+l\n\=i\n\=n\n\=e\_s\+\zs\|a\n\=t\_s\+l\n\=i\n\=n\n\=e\n\=s\_s\+\zs', 'W', stopline) let line = strpart(getline(LineNr), ColNr-1) let lineNr = matchstr(line, '^\d\+\ze') let g:lineNr=lineNr if lineNr !~ '\d\+' keepjumps call setpos(".", saved_pos) return endif if getline(LineNr) =~ '^l\.\d\+' let error = escape(matchstr(getline(LineNr), '^l\.\d\+\s*\zs.*$'), '\.') " let error = escape(matchstr(getline(LineNr), '^l\.\d\+\s*\zs.*$'), '\.') . '\s*' . escape(substitute(strpart(getline(LineNr+1), 0, stridx(getline(LineNr+1), '...')), '^\s*', '', ''), '\.') if g:atp_debugST let g:error = error endif endif " Find the file name/bufnr/winnr where the error occurs. let test = 0 let nr = 0 " There should be a finer way to get the file name if it is split in two " lines. while !test " Some times in the lof file there is a '(' from the source tex file " which might be not closed, then this while loop is used to find " readable file name. let [ startline, startcol ] = searchpairpos('(', '', ')', 'bW') if g:atp_debugST redir! >> /tmp/SyncTex_log let g:startline = startline silent! echomsg " [ startline, startcol ] " . string([ startline, startcol ]) endif " THIS CODE IS NOT WORKING: " if nr >= 1 && [ startline, startcol ] == [ startline_o, startcol_o ] && !test " keepjumps call setpos(".", saved_pos) " let g:debug = "return " . nr " break " endif if !startline if g:atp_debugST silent! echomsg "END startline = " . startline redir END endif keepjumps call setpos(".", saved_pos) return endif let fname = matchstr(strpart(getline(startline), startcol), '^\f\+') " if the file name was broken in the log file in two lines, " get the end of file name from the next line. let tex_extensions = extend(copy(g:atp_tex_extensions), [ 'tex', 'cls', 'sty', 'clo', 'def' ], 0) let pat = '\.\%('.join(tex_extensions, '\|').'\)$' if fname !~# pat let stridx = {} for end in tex_extensions call extend(stridx, { end : stridx(getline(startline+1), "." . end) }) endfor call filter(stridx, "v:val != -1") let StrIdx = {} for end in keys(stridx) call extend(StrIdx, { stridx[end] : end }, 'keep') endfor let idx = min(keys(StrIdx)) let end = get(StrIdx, idx, "") let fname .= strpart(getline(startline+1), 0, idx + len(end) + 1) endif if g:atp_debugST let g:fname = fnamemodify(fname, ":t") let g:dir = fnamemodify(g:fname, ":p:h") let g:pat = pat " if g:fname =~# '^' . escape(fnamemodify(tempname(), ":h"), '\/') " let g:fname = substitute(g:fname, fnamemodify(tempname(), ":h"), b:atp_ProjectDir) " endif endif let test = filereadable(fname) let nr += 1 let [ startline_o, startcol_o ] = deepcopy([ startline, startcol ]) endwhile keepjumps call setpos(".", saved_pos) if g:atp_debugST let g:fname = fname endif " if the file is under texmf directory return unless g:atp_developer = 1 " i.e. do not visit packages and classes. if ( fnamemodify(fname, ':p') =~ '\%(\/\|\\\)texmf' || index(['cls', 'sty', 'bst'], fnamemodify(fname, ":e")) != -1 ) && !g:atp_developer keepjumps call setpos(".", saved_pos) return elseif fnamemodify(fname, ':p') =~ '\%(\/\|\\\)texmf' " comma separated list of options let options = 'nospell' else let options = '' endif let bufnr = bufnr(fname) " let g:bufnr = bufnr let bufwinnr = bufwinnr(bufnr) let log_winnr = bufwinnr("") " Goto found file and correct line. " with bang open file in a new window, " without open file in previous window. if a:bang == "!" if bufwinnr != -1 exe bufwinnr . " wincmd w" exe ':'.lineNr exe 'normal zz' elseif buflisted(bufnr) exe 'split #' . bufnr exe ':'.lineNr exe 'normal zz' else " allows to go to errrors in packages. exe 'split ' . fname exe ':'.lineNr exe 'normal zz' endif else if bufwinnr != -1 exe bufwinnr . " wincmd w" exe ':'.lineNr exe 'normal zz' else exe s:winnr . " wincmd w" if buflisted(bufnr) exe "b " . bufnr exe ':'.lineNr exe 'normal zz' else exe "edit " . fname exe ':'.lineNr exe 'normal zz' endif exe 'normal zz' endif endif " set options if &filetype == "" filetype detect endif for option in split(options, ',') exe "setl " . option endfor " highlight the error if exists("error") && error != "" " let error_pat = escape(error, '\.') " call matchadd("ErrorMsg", '\%'.lineNr.'l' . error_pat) let matchID = matchadd("Error", error, 15) endif if sync setl cursorline " Unset 'cursorline' option when entering the window. exe 'au! WinEnter ' . expand("%:p") . " setl nocursorline" " if exists("matchID") " exe 'au! WinEnter ' . expand("%:p") . " call matchdelete(".matchID.")" " endif exe log_winnr . ' wincmd w' else setl nocursorline endif exe "lcd " . fnameescape(cwd) endfunction command! -buffer -bang SyncTex :call SyncTex() map :SyncTex " nnoremap g :SyncTex augroup ATP_SyncLog au CursorMoved *.log :call SyncTex("", 1) augroup END function! s:SyncXpdfLog(...) let atp_MainFile = atplib#FullPath(b:atp_MainFile) " check the value of g:atp_SyncXpdfLog let check = ( a:0 >= 1 ? a:1 : 1 ) if b:atp_Viewer !~ '^\s*xpdf\>' || b:atp_XpdfServer == "" || check && !g:atp_SyncXpdfLog return endif " let saved_pos = getpos(".") let [ lineNr, colNr ] = searchpos('\[\_d\+\%({[^}]*}\)\=\n\=\]', 'n') let line = strpart(getline(lineNr), colNr-1) . getline(lineNr+1) let pageNr = substitute(matchstr(line, '\[\zs\_d\+\ze\%({[^}]*}\)\=\]'), "\n", "", "g") let g:pageNr = pageNr if pageNr != "" let cmd = "xpdf -remote " . b:atp_XpdfServer . " " . fnamemodify(atp_MainFile, ":r") . ".pdf " . pageNr . " &" let g:cmd = cmd call system(cmd) endif endfunction command! -buffer SyncXpdf :call s:SyncXpdfLog(0) command! -buffer Xpdf :call s:SyncXpdfLog(0) map :SyncXpdf augroup ATP_SyncXpdfLog au CursorMoved *.log :call s:SyncXpdfLog(1) augroup END else echo "No log file" endif endfunction " TeX LOG FILE if &buftype == 'quickfix' setlocal modifiable setlocal autoread endif function! s:TexLog(options) if executable("texloganalyser") let s:command="texloganalyser " . a:options . " " . &l:errorfile echo system(s:command) else echo "Please install 'texloganalyser' to have this functionality. The perl program written by Thomas van Oudenhove." endif endfunction function! s:PdfFonts() if b:atp_OutDir !~ "\/$" b:atp_OutDir=b:atp_OutDir . "/" endif let atp_MainFile = atplib#FullPath(b:atp_MainFile) if executable("pdffonts") let s:command="pdffonts " . fnameescape(fnamemodify(atp_MainFile,":r")) . ".pdf" echo system(s:command) else echo "Please install 'pdffonts' to have this functionality. In 'gentoo' it is in the package 'app-text/poppler-utils'." endif endfunction " function! s:setprintexpr() " if b:atp_TexCompiler == "pdftex" || b:atp_TexCompiler == "pdflatex" " let s:ext = ".pdf" " else " let s:ext = ".dvi" " endif " let &printexpr="system('lpr' . (&printdevice == '' ? '' : ' -P' . &printdevice) . ' " . fnameescape(fnamemodify(expand("%"),":p:r")) . s:ext . "') . + v:shell_error" " endfunction " call s:setprintexpr() function! YesNoCompletion(A,P,L) return ['yes','no'] endfunction "}}} " Ssh printing tools "{{{ Print, Lpstat, ListPrinters " This function can send the output file to local or remote printer. " a:1 = file to print (if not given printing the output file) " a:3 = printing options (give printing optinos or 'default' then use " the variable g:printingoptions) function! s:SshPrint(...) call atplib#outdir() " set the extension of the file to print " if prining the tex output file. if a:0 == 0 || a:0 >= 1 && a:1 == "" let ext = get(g:atp_CompilersDict, b:atp_TexCompiler, "not present") if ext == "not present" echohl WarningMsg echomsg b:atp_TexCompiler . " is not present in g:atp_CompilersDict" echohl Normal return "extension not found" endif if b:atp_TexCompiler =~ "lua" if b:atp_TexOptions == "" || b:atp_TexOptions =~ "output-format=\s*pdf" let ext = ".pdf" else let ext = ".dvi" endif endif endif " set the file to print let pfile = ( a:0 == 0 || (a:0 >= 1 && a:1 == "" ) ? b:atp_OutDir . fnamemodify(expand("%"),":t:r") . ext : a:1 ) " set the printing command let lprcommand = g:atp_lprcommand if a:0 >= 2 let arg_list = copy(a:000) call remove(arg_list,0) let print_options = join(arg_list, " ") endif " print locally or remotely " the default is to print locally (g:atp_ssh=`whoami`@localhost) let server = ( exists("g:atp_ssh") ? strpart(g:atp_ssh,stridx(g:atp_ssh,"@")+1) : "localhost" ) echomsg "Server " . server echomsg "File " . pfile if server =~ 'localhost' let com = lprcommand . " " . print_options . " " . fnameescape(pfile) redraw! echomsg "Printing ... " . com let b:com=com " DEBUG " call system(com) " print over ssh on the server g:atp_ssh with the printer a:1 (or the " default system printer if a:0 == 0 else let com="cat " . fnameescape(pfile) . " | ssh " . g:atp_ssh . " " . lprcommand . " " . print_options echomsg "Printing ... " . com let b:com=com " DEBUG " call system(com) endif endfunction function! Lpr(...) call atplib#outdir() " set the extension of the file to print " if prining the tex output file. if a:0 == 0 || a:0 >= 1 && a:1 == "" let ext = get(g:atp_CompilersDict, b:atp_TexCompiler, "not present") if ext == "not present" echohl WarningMsg echomsg b:atp_TexCompiler . " is not present in g:atp_CompilersDict" echohl Normal return "extension not found" endif if b:atp_TexCompiler =~ "lua" if b:atp_TexOptions == "" || b:atp_TexOptions =~ "output-format=\s*pdf" let ext = ".pdf" else let ext = ".dvi" endif endif endif " set the file to print let pfile = ( a:0 == 0 || (a:0 >= 1 && a:1 == "" ) ? b:atp_OutDir . fnamemodify(expand("%"),":t:r") . ext : a:1 ) " set the printing command let lprcommand = g:atp_lprcommand if a:0 >= 1 let arg_list = copy(a:000) let print_options = join(arg_list, " ") endif let com = lprcommand . " " . print_options . " " . fnameescape(pfile) redraw! echomsg "Printing ... " . com let b:com=com " DEBUG " call system(com) endfunction " The command only prints the output file. fun! s:Lpstat() if exists("g:apt_ssh") let server=strpart(g:atp_ssh,stridx(g:atp_ssh,"@")+1) else let server='locahost' endif if server == 'localhost' echo system("lpstat -l") else echo system("ssh " . g:atp_ssh . " lpstat -l ") endif endfunction " This function is used for completetion of the command SshPrint function! s:ListPrinters(A,L,P) if exists("g:atp_ssh") && g:atp_ssh !~ '@localhost' && g:atp_ssh != "" let com="ssh -q " . g:atp_ssh . " lpstat -a | awk '{print $1}'" else let com="lpstat -a | awk '{print $1}'" endif return system(com) endfunction function! s:ListLocalPrinters(A,L,P) let com="lpstat -a | awk '{print $1}'" return system(com) endfunction " custom style completion function! s:Complete_lpr(ArgLead, CmdLine, CPos) if a:CmdLine =~ '-[Pd]\s\+\w*$' " complete printers return s:ListPrinters(a:ArgLead, "", "") elseif a:CmdLine =~ '-o\s\+[^=]*$' " complete option return join(g:atp_CupsOptions, "\n") elseif a:CmdLine =~ '-o\s\+Collate=\%(\w\|-\)*$' return join(['Collate=True', 'Collate=False'], "\n") elseif a:CmdLine =~ '-o\s\+page-set=\%(\w\|-\)*$' return join(['opage-set=odd', 'page-set=even'], "\n") elseif a:CmdLine =~ '-o\s\+sides=\%(\w\|-\)*$' return join(['sides=two-sided-long-edge', 'sides=two-sided-short-edge', 'sides=one-sided'], "\n") elseif a:CmdLine =~ '-o\s\+outputorder=\%(\w\|-\)*$' return join(['outputorder=reverse', 'outputorder=normal'], "\n") elseif a:CmdLine =~ '-o\s\+page-border=\%(\w\|-\)*$' return join(['page-border=double', 'page-border=none', 'page-border=double-thick', 'page-border=single', 'page-border=single-thick'], "\n") elseif a:CmdLine =~ '-o\s\+job-sheets=\%(\w\|-\)*$' return join(['job-sheets=none', 'job-sheets=classified', 'job-sheets=confidential', 'job-sheets=secret', 'job-sheets=standard', 'job-sheets=topsecret', 'job-sheets=unclassified'], "\n") elseif a:CmdLine =~ '-o\s\+number-up-layout=\%(\w\|-\)*$' return join(['number-up-layout=btlr', 'number-up-layout=btrl', 'number-up-layout=lrbt', 'number-up-layout=lrtb', 'number-up-layout=rlbt', 'number-up-layout=rltb', 'number-up-layout=tblr', 'number-up-layout=tbrl'], "\n") elseif a:CmdLine =~ '-o\s\+position=\%(\w\|-\)*$' return join(['position=center', 'position=top', 'position=left', 'position=right', 'position=top-left', 'position=top-right', \ 'position=bottom', 'position=bottom-left', 'position=bottom-right'], "\n") endif return "" endfunction function! s:CompleteLocal_lpr(ArgLead, CmdLine, CPos) if a:CmdLine =~ '-[Pd]\s\+\w*$' " complete printers return s:ListLocalPrinters(a:ArgLead, "", "") elseif a:CmdLine =~ '-o\s\+[^=]*$' " complete option return join(g:atp_CupsOptions, "\n") elseif a:CmdLine =~ '-o\s\+Collate=\%(\w\|-\)*$' return join(['Collate=True', 'Collate=False'], "\n") elseif a:CmdLine =~ '-o\s\+page-set=\%(\w\|-\)*$' return join(['opage-set=odd', 'page-set=even'], "\n") elseif a:CmdLine =~ '-o\s\+sides=\%(\w\|-\)*$' return join(['sides=two-sided-long-edge', 'sides=two-sided-short-edge', 'sides=one-sided'], "\n") elseif a:CmdLine =~ '-o\s\+outputorder=\%(\w\|-\)*$' return join(['outputorder=reverse', 'outputorder=normal'], "\n") elseif a:CmdLine =~ '-o\s\+page-border=\%(\w\|-\)*$' return join(['page-border=double', 'page-border=none', 'page-border=double-thick', 'page-border=single', 'page-border=single-thick'], "\n") elseif a:CmdLine =~ '-o\s\+job-sheets=\%(\w\|-\)*$' return join(['job-sheets=none', 'job-sheets=classified', 'job-sheets=confidential', 'job-sheets=secret', 'job-sheets=standard', 'job-sheets=topsecret', 'job-sheets=unclassified'], "\n") elseif a:CmdLine =~ '-o\s\+number-up-layout=\%(\w\|-\)*$' return join(['number-up-layout=btlr', 'number-up-layout=btrl', 'number-up-layout=lrbt', 'number-up-layout=lrtb', 'number-up-layout=rlbt', 'number-up-layout=rltb', 'number-up-layout=tblr', 'number-up-layout=tbrl'], "\n") elseif a:CmdLine =~ '-o\s\+position=\%(\w\|-\)*$' return join(['position=center', 'position=top', 'position=left', 'position=right', 'position=top-left', 'position=top-right', \ 'position=bottom', 'position=bottom-left', 'position=bottom-right'], "\n") endif return "" endfunction " }}} " Open Library Command " {{{ :Open command! -nargs=? -bang -complete=file Open call atplib#Open(, g:atp_LibraryPath, g:atp_OpenTypeDict, ) let g:atp_open_completion = [] " -complete=customlist,ATP_CompleteOpen " function! ATP_CompleteOpen(ArgLead, CmdLead, CurPos) " return filter(deepcopy(g:atp_open_completion), "v:val =~ '^' . a:ArgLead") " endfunction " }}} " ToDo notes " {{{ ToDo " " TODO if the file was not found ask to make one. function! ToDo(keyword,stop,...) if a:0 == 0 let bufname = bufname("%") else let bufname = a:1 endif " read the buffer let texfile=getbufline(bufname, 1, "$") " find ToDos let todo = {} let nr=1 for line in texfile if line =~ '%.*' . a:keyword call extend(todo, { nr : line }) endif let nr += 1 endfor " Show ToDos echohl atp_Todo if len(keys(todo)) == 0 echomsg " List for '%.*" . a:keyword . "' in '" . bufname . "' is empty." return endif echomsg " List for '%.*" . a:keyword . "' in '" . bufname . "':" let sortedkeys=sort(keys(todo), "atplib#CompareNumbers") for key in sortedkeys " echo the todo line. echomsg key . " " . substitute(substitute(todo[key],'%','',''),'\t',' ','g') let true = 1 let a = 1 let linenr = key " show all comment lines right below the found todo line. while true && texfile[linenr] !~ '%.*\c\' let linenr=key+a-1 if texfile[linenr] =~ '\s*%' && texfile[linenr] !~ a:stop " make space of length equal to len(linenr) let space="" let j=0 while j < len(linenr) let space=space . " " let j+=1 endwhile echomsg space . " " . substitute(substitute(texfile[linenr],'%','',''),'\t',' ','g') else let true = 0 endif let a += 1 endwhile endfor echohl None endfunction " }}} " This functions reloads ATP (whole or just a function) " {{{ RELOAD if !exists("g:debug_atp_plugin") let g:debug_atp_plugin=0 endif if g:debug_atp_plugin==1 && !exists("*Reload") " Reload() - reload all the tex_apt functions " Reload(func1,func2,...) reload list of functions func1 and func2 " function! Reload(...) " let pos_saved=getpos(".") " let bufname=fnamemodify(expand("%"),":p") " " if a:0 == 0 " let runtime_path=split(&runtimepath,',') " echo "Searching for atp plugin files" " let file_list=['ftplugin/tex_atp.vim', 'ftplugin/fd_atp.vim', " \ 'ftplugin/bibsearch_atp.vim', 'ftplugin/toc_atp.vim', " \ 'autoload/atplib.vim', 'ftplugin/atp_LatexBox.vim', " \ 'indent/tex_atp.vim' ] " let file_path=[] " for file in file_list " call add(file_path,globpath(&rtp,file)) " endfor " " if exists("b:atp_debug") " " if b:atp_debug == "v" || b:atp_debug == "verbose" " " echomsg string(file_path) " " endif " " endif " for file in file_path " echomsg "deleting FUNCTIONS and VARIABLES from " . file " let atp=readfile(file) " for line in atp " let function_name=matchstr(line,'^\s*fun\%(ction\)\?!\?\s\+\zs\<[^(]*\>\ze(') " if function_name != "" && function_name != "Reload" " if exists("*" . function_name) " if exists("b:atp_debug") " if b:atp_debug == "v" || b:atp_debug == "verbose" " echomsg "deleting function " . function_name " endif " endif " execute "delfunction " . function_name " endif " endif " let variable_name=matchstr(line,'^\s*let\s\+\zsg:[a-zA-Z_^{}]*\ze\>') " if exists(variable_name) " execute "unlet ".variable_name " if exists("b:atp_debug") " if b:atp_debug == "v" || b:atp_debug == "verbose" " echomsg "unlet ".variable_name " endif " endif " endif " endfor " endfor " else " if a:1 != "maps" && a:1 != "reload" " let f_list=split(a:1,',') " let g:f_list=f_list " for function in f_list " execute "delfunction " . function " if exists("b:atp_debug") " if b:atp_debug == "v" || b:atp_debug == "verbose" " echomsg "delfunction " . function " endif " endif " endfor " endif " endif " augroup! ATP_auTeX " " Do not write project script file while saving the file. " let atp_ProjectScript = ( exists("g:atp_ProjectScript") ? g:atp_ProjectScript : -1 ) " let g:atp_ProjectScript = 0 " w " if atp_ProjectScript == -1 " unlet g:atp_ProjectScript " else " let g:atp_ProjectScript = atp_ProjectScript " endif " " THIS IS THE SLOW WAY: " bd! " execute "edit " . fnameescape(bufname) " keepjumps call setpos(".",pos_saved) " " This could be faster: but aparently doesn't work. " " execute "source " . file_path[0] " endfunction " Source options.vim try function! ReloadATP(bang) " First source the option file let common_file = globpath(&rtp, 'ftplugin/ATP_files/common.vim') let options_file = globpath(&rtp, 'ftplugin/ATP_files/options.vim') let g:atp_reload_functions = ( a:bang == "!" ? 1 : 0 ) let g:atp_reload = 1 if a:bang == "" execute "source " . common_file execute "source " . options_file let g:atp_reload = 0 " Then source atprc file if filereadable(globpath($HOME, '/.atprc.vim', 1)) && has("unix") " Note: in $HOME/.atprc file the user can set all the local buffer " variables without using autocommands let path = globpath($HOME, '/.atprc.vim', 1) execute 'source ' . fnameescape(path) else let path = get(split(globpath(&rtp, "**/ftplugin/ATP_files/atprc.vim"), '\n'), 0, "") if path != "" execute 'source ' . fnameescape(path) endif endif else let tex_atp_file = globpath(&rtp, 'ftplugin/tex_atp.vim') execute "source " . tex_atp_file " This reloads all functions except autoload/atplib.vim let g:atp_reload = 0 let g:atp_reload_functions = 0 endif endfunction catch /E127:/ " Cannot redefine function, function is in use. endtry endif " }}} " This functions prints preambule " {{{ Preambule function! Preambule() let loclist = getloclist(0) let winview = winsaveview() exe '1lvimgrep /^[^%]*\\begin\s*{\s*document\s*}/j ' . fnameescape(b:atp_MainFile) let linenr = get(get(getloclist(0), 0, {}), 'lnum', 'nomatch') if linenr != 'nomatch' if expand("%:p") != atplib#FullPath(b:atp_MainFile) let cfile = expand("%:p") exe "keepalt edit " . b:atp_MainFile endif exe "1," . (linenr-1) . "print" if exists("cfile") exe "keepalt edit " . cfile endif call winrestview(winview) else echomsg " Not found \begin{document}." endif endfunction " }}} " Get bibdata from ams " {{{ AMSGet try function! GetAMSRef(what, bibfile) let what = substitute(a:what, '\s\+', ' ', 'g') let what = substitute(what, '%', '%25', 'g') let what = substitute(what, ',', '%2C', 'g') let what = substitute(what, ':', '%3A', 'g') let what = substitute(what, ';', '%3B', 'g') let what = substitute(what, '/', '%2F', 'g') let what = substitute(what, '?', '%3F', 'g') let what = substitute(what, '+', '%2B', 'g') let what = substitute(what, '=', '%3D', 'g') let what = substitute(what, '#', '%23', 'g') let what = substitute(what, '\$', '%24', 'g') let what = substitute(what, '&', '%26', 'g') let what = substitute(what, '@', '%40', 'g') let what = substitute(what, ' ', '+', 'g') let tmpdir=tempname() call mkdir(tmpdir, "p") let atpbib_WgetOutputFile = tmpdir . g:atpbib_pathseparator . "amsref.html" if a:bibfile != "nobibfile" let cmd = g:atpbib_wget . " -O " . atpbib_WgetOutputFile . ' "http://www.ams.org/mathscinet-mref?ref='.what.'&dataType=bibtex"' else let cmd = g:atpbib_wget . " -O " . atpbib_WgetOutputFile . ' "http://www.ams.org/mathscinet-mref?ref='.what.'&dataType=tex"' endif call system(cmd) let g:cmd=cmd let loclist = getloclist(0) try exe '1lvimgrep /\CNo Unique Match Found/j ' . fnameescape(atpbib_WgetOutputFile) catch /E480/ endtry if len(getloclist(0)) return ['NoUniqueMatch'] endif if len(b:AllBibFiles) > 0 let pattern = '@\%(article\|book\%(let\)\=\|conference\|inbook\|incollection\|\%(in\)\=proceedings\|manual\|masterthesis\|misc\|phdthesis\|techreport\|unpublished\)\s*{\|^\s*\%(ADDRESS\|ANNOTE\|AUTHOR\|BOOKTITLE\|CHAPTER\|CROSSREF\|EDITION\|EDITOR\|HOWPUBLISHED\|INSTITUTION\|JOURNAL\|KEY\|MONTH\|NOTE\|NUMBER\|ORGANIZATION\|PAGES\|PUBLISHER\|SCHOOL\|SERIES\|TITLE\|TYPE\|VOLUME\|YEAR\|MRCLASS\|MRNUMBER\|MRREVIEWER\)\s*=\s*.*$' try exe 'lvimgrep /'.pattern.'/j ' . fnameescape(atpbib_WgetOutputFile) catch /E480:/ endtry let data = getloclist(0) call setloclist(0, loclist) if !len(data) echohl WarningMsg echomsg "Nothing found." echohl None return [0] endif let linenumbers = map(copy(data), 'v:val["lnum"]') let begin = min(linenumbers) let end = max(linenumbers) let bufnr = bufnr(atpbib_WgetOutputFile) " To use getbufline() buffer must be loaded. It is enough to use :buffer " command because vimgrep loads buffer and then unloads it. execute "buffer " . bufnr let bibdata = getbufline(bufnr, begin, end) execute "bdelete " . bufnr let type = matchstr(bibdata[0], '@\%(article\|book\%(let\)\=\|conference\|inbook\|incollection\|\%(in\)\=proceedings\|manual\|masterthesis\|misc\|phdthesis\|techreport\|unpublished\)\ze\s*\%("\|{\|(\)') " Suggest Key: let bibkey = input("Provide a key (Enter for the AMS bibkey): ") if !empty(bibkey) let bibdata[0] = type . '{' . bibkey . ',' else let bibdata[0] = substitute(matchstr(bibdata[0], '@\w*.*$'), '\(@\w*\)\(\s*\)', '\1', '') " This will be only used to echomsg: let bibkey = matchstr(bibdata[0], '@\w*.\s*\zs[^,]*') endif call add(bibdata, "}") " Open bibfile and append the bibdata: execute "silent! edit " . a:bibfile if getline(line('$')) !~ '^\s*$' let bibdata = extend([''], bibdata) endif call append(line('$'), bibdata) normal GG echohl WarningMsg echomsg "Bibkey " . bibkey . " appended to: " . a:bibfile echohl Normal else " If the user is using \begin{bibliography} environment. let pattern = '^' try exe 'lvimgrep /'.pattern.'/j ' . fnameescape(atpbib_WgetOutputFile) catch /E480:/ endtry let data = getloclist(0) if !len(data) echohl WarningMsg echomsg "Nothing found." echohl None return [0] elseif len(data) > 1 echoerr "ATP Error: AMSRef vimgrep pattern error. You can send a bug report. Please include the exact :ATPRef command." endif let bibref = '\bibitem{} ' . matchstr(data[0]['text'], '^\zs.*\ze<\/td><\/tr>') let g:atp_bibref = bibref exe "let @" . g:atp_bibrefRegister . ' = "' . escape(bibref, '\') . '"' let bibdata = [ bibref ] endif let g:atp_bibdata = bibdata call system("rm -rf " . fnamemodify(atpbib_WgetOutputFile, ":h")) return bibdata endfunction catch /E127/ endtry function! AMSRef(bang, what) if !exists("b:AllBibFiles") call FindInputFiles(b:atp_MainFile) endif if len(b:AllBibFiles) > 1 let bibfile = inputlist(extend("Which bib file to use?", b:AllBibFiles)) elseif len(b:AllBibFiles) == 1 let bibfile = b:AllBibFiles[0] elseif !len(b:AllBibFiles) let bibfile = "nobibfile" endif let return=GetAMSRef(a:what, bibfile) " let g:bang=a:bang " let g:bibfile=bibfile " let g:return=return if a:bang == "" && bibfile != "nobibfile" && return != [0] && return != ['NoUniqueMatch'] silent! w silent! bd elseif bibfile == "nobibfile" && return != [0] && return != ['NoUniqueMatch'] redraw echohl WarningMsg echomsg "Found bib data is in register " . g:atp_bibrefRegister echohl Normal elseif return[0] == 'NoUniqueMatch' redraw echohl WarningMsg echomsg "No Unique Match Found" echohl None endif endfunction "}}} " Count Words " {{{ WordCount() ShowWordCount() function! WordCount(bang) let g:atp_WordCount = {} for file in keys(filter(copy(b:TypeDict), 'v:val == ''input''')) + [ b:atp_MainFile ] let wcount = substitute(system("detex -n " . fnameescape(file) . " | wc -w "), '\D', '', 'g') call extend(g:atp_WordCount, { file : wcount }) endfor " sum values let val = values(g:atp_WordCount) let wc_sum = 0 for i in val let wc_sum += i endfor return wc_sum endfunction function! ShowWordCount(bang) let wc = WordCount(a:bang) let c = 0 if a:bang == "!" echo g:atp_WordCount[b:atp_MainFile] . "\t" . b:atp_MainFile for file in b:ListOfFiles if get(g:atp_WordCount, file, "NOFILE") != "NOFILE" let c=1 echo g:atp_WordCount[file] . "\t" . file endif endfor if c echomsg wc endif else echomsg wc . " " . b:atp_MainFile endif endfunction "}}} " Wdiff " {{{ " Needs wdiff program. function! Wdiff(new_file, old_file) if !executable("wdiff") echohl WarningMsg echo "You need to install GNU wdiff program." echohl Normal return 1 endif " Operate on temporary copies: try let new_file = readfile(a:new_file) catch /E484/ echohl ErrorMsg echomsg "Can't open file " . a:new_file return 1 endtry try let old_file = readfile(a:old_file) catch /E484/ echohl ErrorMsg echomsg "Can't open file " . a:old_file return 1 endtry " Remove the preambule: let new_pend=0 for line in new_file if line =~ '^[^%]*\\begin{document}' break endif let new_pend+=1 endfor let old_pend=0 for line in new_file if line =~ '^[^%]*\\begin{document}' break endif let old_pend+=1 endfor let new_preambule = remove(new_file, 0, new_pend) let old_preambule = remove(old_file, 0, old_pend) let g:new_preambule = new_preambule let g:old_preambule = old_preambule let g:new_file = new_file let g:old_file = old_file let new_tmp = tempname() let old_tmp = tempname() if new_preambule != old_preambule let which_pre=inputlist(["Wich preambule to use:", "(1) from " . a:new_file, "(2) from " . a:old_file]) if which_pre != 1 && which_pre != 2 return 0 endif else let which_pre = 1 endif execute "keepalt edit " . new_tmp call append(0, new_file) let buf_new = bufnr("%") "delete all comments if expand("%:p") == new_tmp silent! execute ':%g/^\s*%/d' silent! execute ':%s/\s*\\\@!%.*$//g' silent! write silent! bdelete else return 1 endif execute "keepalt edit " . old_tmp call append(0, old_file) let buf_old = bufnr("%") "delete all comments if expand("%:p") == old_tmp silent! execute ':%g/^\s*%/d' silent! execute ':%s/\s*\\\@!%.*$//g' silent! write silent! bdelete else return 1 endif " make wdiff: if filereadable("/tmp/wdiff.tex") call delete("/tmp/wdiff.tex") endif " call system("wdiff -w '{\\textcolor{red}{=}' -x '\\textcolor{red}{=}}' -y '{\\textcolor{blue}{+}' -z '\\textcolor{blue}{+}}' " . new_tmp . " " . old_tmp . " > /tmp/wdiff.tex") call system("wdiff " . "-w '\\{=' -x '=\\}' -y '\\{+' -z '+\\}'" . " " . new_tmp . " " . old_tmp . " > /tmp/wdiff.tex") split /tmp/wdiff.tex " Set atp let b:atp_autex=0 let b:atp_ProjectScript=0 " These do not match multiline changes! let s:atp_IDdelete = matchadd('DiffDelete', '\\{=\zs\%(=\\}\@!\|=\\\@!}\|=\@!\\}\|[^}=\\]\|=\\\@!\|\\}\@!\|=\@ map [s ?\\{[=+]\_.*[+=]\\} function! NiceDiff() let saved_pos=getpos(".") keepjumps %s/\\{=\(\%(=\\}\@!\|=\\\@!}\|=\@!\\}\|[^}=\\]\|=\\\@!\|\\}\@!\|=\@ WrapSelection :call WrapSelection('')i vmap InteligentWrapSelection :call InteligentWrapSelection('')i nnoremap ToggleStar :call ToggleStar() nnoremap ToggleEnvForward :call ToggleEnvironment(0, 1) nnoremap ToggleEnvBackward :call ToggleEnvironment(0, -1) nnoremap ChangeEnv :call ToggleEnvironment(1) nnoremap TexDoc :TexDoc " Commands: "{{{1 command! -buffer -nargs=* -complete=file Wdiff :call Wdiff() command! -buffer -nargs=? -range WrapSelection :call WrapSelection() command! -buffer -nargs=? -range InteligentWrapSelection :call InteligentWrapSelection() command! -buffer TexAlign :call TexAlign() command! -buffer ToggleStar :call ToggleStar() command! -buffer -nargs=? ToggleEnv :call ToggleEnvironment(0, ) command! -buffer -nargs=* -complete=customlist,EnvCompletion ChangeEnv :call ToggleEnvironment(1, ) command! -buffer -nargs=* -complete=customlist,TeXdoc_complete TexDoc :call TexDoc() command! -buffer -bang Delete :call Delete() nmap Delete :call Delete("") command! -buffer OpenLog :call OpenLog() nnoremap OpenLog :call OpenLog() command! -buffer TexLog :call TexLog() nnoremap TexLog :call TexLog() command! -buffer PdfFonts :call PdfFonts() nnoremap PdfFonts :call PdfFonts() command! -complete=custom,s:Complete_lpr -buffer -nargs=* SshPrint :call SshPrint("", ) command! -complete=custom,s:CompleteLocal_lpr -buffer -nargs=* Lpr :call Lpr() nnoremap SshPrint :SshPrint command! -buffer Lpstat :call Lpstat() nnoremap Lpstat :call Lpstat() command! -buffer ListPrinters :echo ListPrinters("", "", "") " List Packages: command! -buffer ShowPackages :let b:atp_PackageList = atplib#GrepPackageList() | echo join(b:atp_PackageList, "\n") command! -buffer -nargs=? -complete=buffer ToDo :call ToDo('\c\','\s*%\c.*\',) command! -buffer -nargs=? -complete=buffer Note :call ToDo('\c\','\s*%\c.*\',) command! -buffer ReloadATP :call ReloadATP("!") command! -bang -buffer -nargs=1 AMSRef :call AMSRef(, ) command! -buffer Preambule :call Preambule() command! -bang WordCount :call ShowWordCount() " vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1 ftplugin/ATP_files/helpfunctions.vim [[[1 170 " Author: Marcin Szamotulski " Description: This file contains help commands and variables (for mappings used by ATP) " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " Language: tex " Last Change: let s:sourced = !exists("s:loaded") ? 0 : 1 if !s:sourced " {{{1 Help Math IMAPS function! HelpMathIMaps() if exists("g:no_plugin_maps") || exists("g:no_atp_maps") echomsg "ATP maps are turned off" return '' endif let infty_leader = (g:atp_imap_first_leader == "#" ? "\\" : g:atp_imap_first_leader ) let g:help_mathimaps = '' \."\n MATH IMAPS" \."\n has value g:atp_imap_first_leader" \."\n ".g:atp_imap_first_leader."a \\alpha ".g:atp_imap_first_leader."b \\beta" \."\n ".g:atp_imap_first_leader."g \\gamma ".g:atp_imap_first_leader."d \\delta" \."\n ".g:atp_imap_first_leader."e \\epsilon ".g:atp_imap_first_leader."ve \\varepsilon" \."\n ".g:atp_imap_first_leader."z \\zeta ".g:atp_imap_first_leader."h \\eta" \."\n ".g:atp_imap_first_leader."o \\theta ".g:atp_imap_first_leader."vo \\vartheta" \."\n ".g:atp_imap_first_leader."i \\iota ".g:atp_imap_first_leader."k \\kappa" \."\n ".g:atp_imap_first_leader."l \\lambda ".g:atp_imap_first_leader."m \\mu" \."\n ".g:atp_imap_first_leader."n \\nu ".g:atp_imap_first_leader."x \\xi" \."\n ".g:atp_imap_first_leader."p \\pi ".g:atp_imap_first_leader."r \\rho" \."\n ".g:atp_imap_first_leader."s \\sigma ".g:atp_imap_first_leader."vs \\varsigma" \."\n ".g:atp_imap_first_leader."t \\tau ".g:atp_imap_first_leader."u \\upsilon" \."\n ".g:atp_imap_first_leader."f \\phi ".g:atp_imap_first_leader."c \\chi" \."\n ".g:atp_imap_first_leader."y \\psi ".g:atp_imap_first_leader."w \\omega" \."\n" \."\n ".g:atp_imap_first_leader."G \\Gamma ".g:atp_imap_first_leader."D \\Delta" \."\n ".g:atp_imap_first_leader."Z \\mathrm{Z} ".g:atp_imap_first_leader."O \\Theta" \."\n ".g:atp_imap_first_leader."L \\Lambda ".g:atp_imap_first_leader."M \\Mu" \."\n ".g:atp_imap_first_leader."N \\Nu ".g:atp_imap_first_leader."P \\Pi" \."\n ".g:atp_imap_first_leader."S \\Sigma ".g:atp_imap_first_leader."U \\Upsilon" \."\n ".g:atp_imap_first_leader."F \\Phi ".g:atp_imap_first_leader."Y \\Psi" \."\n ".g:atp_imap_first_leader."W \\Omega" \."\n" \."\n ".g:atp_imap_first_leader."+ \\bigcup ".g:atp_imap_first_leader."- \\setminus" \."\n ".infty_leader."8 \\infty ".g:atp_imap_first_leader."& \\wedge" \."\n ". "^^ ^{} ". "__ _{}" \."\n ".g:atp_imap_third_leader."m \\(\\) ".g:atp_imap_third_leader."M \\[\\] has value g:atp_imap_third_leader" return g:help_mathimaps endfunction silent call HelpMathIMaps() " {{{1 Help Environment IMAPS function! HelpEnvIMaps() if exists("g:no_plugin_maps") || exists("g:no_atp_maps") echomsg "ATP maps are turned off" return '' endif let g:help_envimaps = '' \."\n ENVIRONMENT IMAPS" \."\n has value g:atp_imap_third_leader" \."\n ".g:atp_imap_third_leader."b \\begin{} ".g:atp_imap_third_leader."e \\end{}" \."\n ".g:atp_imap_third_leader."t theorem ".g:atp_imap_third_leader."d definition" \."\n ".g:atp_imap_third_leader."p proposition ".g:atp_imap_third_leader."l lemma" \."\n ".g:atp_imap_third_leader."r remark ".g:atp_imap_third_leader."C corollary" \."\n ".g:atp_imap_third_leader."p proof ".g:atp_imap_third_leader."x example" \."\n ".g:atp_imap_third_leader."n note " \."\n" \."\n ".g:atp_imap_third_leader."E enumerate ".g:atp_imap_third_leader."I itemize" \."\n ".g:atp_imap_third_leader."i \\item" \."\n" \."\n ".g:atp_imap_third_leader."a align ".g:atp_imap_third_leader."e equation" \."\n" \."\n ".g:atp_imap_third_leader."L flushleft ".g:atp_imap_third_leader."R flushright" \."\n ".g:atp_imap_third_leader."c center" \."\n" \."\n ".g:atp_imap_third_leader."T tikzpicture" \."\n" \."\n ".g:atp_imap_third_leader."f frame" return g:help_envimaps endfunction silent call HelpEnvIMaps() " {{{1 Help VMaps function! HelpVMaps() if exists("g:no_plugin_maps") || exists("g:no_atp_maps") echomsg "ATP maps are turned off" return '' endif " Substitute with maplocalleader if !exists("maplocalleader") let maplocalleader = "\\" endif let l:atp_vmap_text_font_leader = ( g:atp_vmap_text_font_leader == "" ? maplocalleader : g:atp_vmap_text_font_leader ) let l:atp_vmap_environment_leader = ( g:atp_vmap_environment_leader == "" ? maplocalleader : g:atp_vmap_environment_leader ) let l:atp_vmap_bracket_leader = ( g:atp_vmap_bracket_leader == "" ? maplocalleader : g:atp_vmap_bracket_leader ) let l:atp_vmap_big_bracket_leader = ( g:atp_vmap_big_bracket_leader =~ "" ? substitute(g:atp_vmap_big_bracket_leader, '', maplocalleader, '') : g:atp_vmap_big_bracket_leader ) let g:help_vmaps = '' \."\n has value g:atp_vmap_text_font_leader" \."\n KEYMAP TEXT MODE MATH MODE" \."\n ".l:atp_vmap_text_font_leader."rm \\textrm{} \\mathrm{}" \."\n ".l:atp_vmap_text_font_leader."em \\emph{} \\mathit{}" \."\n ".l:atp_vmap_text_font_leader."it \\textit{} \\mathit{}" \."\n ".l:atp_vmap_text_font_leader."sf \\textsf{} \\mathsf{}" \."\n ".l:atp_vmap_text_font_leader."tt \\texttt{} \\mathtt{}" \."\n ".l:atp_vmap_text_font_leader."bf \\textbf{} \\mathbf{}" \."\n ".l:atp_vmap_text_font_leader."bb \\textbf{} \\mathbb{}" \."\n ".l:atp_vmap_text_font_leader."bb \\textbf{} \\mathbb{}" \."\n ".l:atp_vmap_text_font_leader."sl \\textsl{}" \."\n ".l:atp_vmap_text_font_leader."sc \\textsc{}" \."\n ".l:atp_vmap_text_font_leader."up \\textup{}" \."\n ".l:atp_vmap_text_font_leader."md \\textmd{}" \."\n ".l:atp_vmap_text_font_leader."un \\underline{} \\underline{}" \."\n ".l:atp_vmap_text_font_leader."ov \\overline{} \\overline{}" \."\n ".l:atp_vmap_text_font_leader."no \\textnormal{} \\mathnormal{}" \."\n ".l:atp_vmap_text_font_leader."cal \\mathcal{}" \."\n " \."\n MODE INDEPENDENT VMAPS:" \."\n has value g:atp_vmap_environment_leader" \."\n ".l:atp_vmap_environment_leader."C wrap in center environment" \."\n ".l:atp_vmap_environment_leader."L wrap in flushleft environment" \."\n ".l:atp_vmap_environment_leader."R wrap in flushright environment" \."\n ".l:atp_vmap_environment_leader."E wrap in equation environment" \."\n ".l:atp_vmap_environment_leader."A wrap in align environment" \."\n " \."\n has value g:atp_vmap_bracket_leader" \."\n ".l:atp_vmap_bracket_leader."( (:) ".l:atp_vmap_bracket_leader.") (:)" \."\n ".l:atp_vmap_bracket_leader."[ [:] ".l:atp_vmap_bracket_leader."] [:]" \."\n ".l:atp_vmap_bracket_leader."{ {:} ".l:atp_vmap_bracket_leader."} {:}" \."\n ".l:atp_vmap_bracket_leader."\\{ \\{:\\} ".l:atp_vmap_bracket_leader."\\} \\{:\\}" \."\n m \\(:\\) M \\[:\\] " \."\n " \."\n has value g:atp_vmap_big_bracket_leader" \."\n ".l:atp_vmap_big_bracket_leader."( \\left(:\\right) ".l:atp_vmap_big_bracket_leader.") \\left(:\\right)" \."\n ".l:atp_vmap_big_bracket_leader."[ \\left[:\\right] ".l:atp_vmap_big_bracket_leader."] \\left[:\\right]" \."\n ".l:atp_vmap_big_bracket_leader."{ \\left{:\\right} ".l:atp_vmap_big_bracket_leader."} \\left{:\\right}" \."\n ".l:atp_vmap_big_bracket_leader."\\{ \\left\\{:\\right\\} ".l:atp_vmap_big_bracket_leader."\\} \\left\\{:\\right\\}" \."\n " \."\n ".l:atp_vmap_text_font_leader."f \\usefont{".g:atp_font_encoding."}{}{}{}\\selectfont" return g:help_vmaps endfunction silent call HelpVMaps() " {{{1 Help IMaps " function! HelpIMaps() " let tc_imap = maparg(" ", 'i') =~# 'atplib#TabCompletion' ? '' : " \ maparg(" ", 'i') =~# 'atplib#TabCompletion' ? '' : "" " let netc_imap = tc_imap == "" ? "" : tc_imap == "" ? "" : "" " let g:help_imaps = '' " \."\n has value g:atp_vmap_text_font_leader" " \."\n ".tc_imap." "."Completion (expert mode)" " \."\n ".netc_imap." "."Completion (non-expert mode)" " endfunction " silent call HelpIMaps() " command! -buffer HelpIMaps :echo HelpIMaps() " }}}1 endif " Commands: " {{{ command! -buffer HelpMathIMaps :echo HelpMathIMaps() command! -buffer HelpEnvIMaps :echo HelpEnvIMaps() command! -buffer HelpVMaps :echo HelpVMaps() "}}} " vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1 ftplugin/ATP_files/vimcomplete.bst [[[1 306 ENTRY { address author booktitle chapter doi edition editor eid howpublished institution isbn issn journal key month note number organization pages publisher school series title type volume year } {} { label } STRINGS { s t} FUNCTION {output} { 's := %purify$ %"}{" * write$ "||" * write$ s } FUNCTION {fin.entry} %{ "}" * write$ { write$ newline$ } FUNCTION {not} { { #0 } { #1 } if$ } FUNCTION {and} { 'skip$ { pop$ #0 } if$ } FUNCTION {or} { { pop$ #1 } 'skip$ if$ } FUNCTION {field.or.null} { duplicate$ empty$ { pop$ "" } 'skip$ if$ } FUNCTION {capitalize} { "u" change.case$ "t" change.case$ } FUNCTION {space.word} { " " swap$ * " " * } FUNCTION {bbl.and} { "&"} FUNCTION {bbl.etal} { "et al." } INTEGERS { nameptr namesleft numnames } STRINGS { bibinfo} FUNCTION {format.names} { duplicate$ empty$ 'skip$ { 's := "" 't := #1 'nameptr := s num.names$ 'numnames := numnames 'namesleft := { namesleft #0 > } { s nameptr %"{vv~}{ll}{, f.}{, jj}" "{vv }{ll}{}{}" format.name$ 't := nameptr #1 > { namesleft #1 > { ", " * t * } { s nameptr "{ll}" format.name$ duplicate$ "others" = { 't := } { pop$ } if$ t "others" = { " " * bbl.etal * } { bbl.and space.word * t * } if$ } if$ } 't if$ nameptr #1 + 'nameptr := namesleft #1 - 'namesleft := } while$ } if$ } FUNCTION {format.authors} { author empty$ {editor format.names} {author format.names} if$ } FUNCTION {format.title} { title duplicate$ empty$ 'skip$ { "t" change.case$ } if$ } FUNCTION {output.label} { newline$ %"{" cite$ * write$ cite$ write$ "" } FUNCTION {format.date} { "" duplicate$ empty$ year duplicate$ empty$ { swap$ 'skip$ { "there's a month but no year in " cite$ * warning$ } if$ * } { swap$ 'skip$ { swap$ " " * swap$ } if$ * } if$ } FUNCTION {output.entry} { 's := output.label s output format.authors output format.date output format.title output fin.entry } FUNCTION {default.type} {"?" output.entry} FUNCTION {article} {"a" output.entry} FUNCTION {book} {"B" output.entry} FUNCTION {booklet} {"k" output.entry} FUNCTION {conference} {"f" output.entry} FUNCTION {inbook} {"b" output.entry} FUNCTION {incollection} {"c" output.entry} FUNCTION {inproceedings} {"p" output.entry} FUNCTION {manual} {"m" output.entry} FUNCTION {mastersthesis} {"Master" output.entry} FUNCTION {misc} {"-" output.entry} FUNCTION {phdthesis} {"PhD" output.entry} FUNCTION {proceedings} {"P" output.entry} FUNCTION {techreport} {"r" output.entry} FUNCTION {unpublished} {"u" output.entry} READ FUNCTION {sortify} { purify$ "l" change.case$ } INTEGERS { len } FUNCTION {chop.word} { 's := 'len := s #1 len substring$ = { s len #1 + global.max$ substring$ } 's if$ } FUNCTION {sort.format.names} { 's := #1 'nameptr := "" s num.names$ 'numnames := numnames 'namesleft := { namesleft #0 > } { s nameptr "{vv{ } }{ll{ }}{ f{ }}{ jj{ }}" format.name$ 't := nameptr #1 > { " " * namesleft #1 = t "others" = and { "zzzzz" * } { t sortify * } if$ } { t sortify * } if$ nameptr #1 + 'nameptr := namesleft #1 - 'namesleft := } while$ } FUNCTION {sort.format.title} { 't := "A " #2 "An " #3 "The " #4 t chop.word chop.word chop.word sortify #1 global.max$ substring$ } FUNCTION {author.sort} { author empty$ { key empty$ { "to sort, need author or key in " cite$ * warning$ "" } { key sortify } if$ } { author sort.format.names } if$ } FUNCTION {author.editor.sort} { author empty$ { editor empty$ { key empty$ { "to sort, need author, editor, or key in " cite$ * warning$ "" } { key sortify } if$ } { editor sort.format.names } if$ } { author sort.format.names } if$ } FUNCTION {author.organization.sort} { author empty$ { organization empty$ { key empty$ { "to sort, need author, organization, or key in " cite$ * warning$ "" } { key sortify } if$ } { "The " #4 organization chop.word sortify } if$ } { author sort.format.names } if$ } FUNCTION {editor.organization.sort} { editor empty$ { organization empty$ { key empty$ { "to sort, need editor, organization, or key in " cite$ * warning$ "" } { key sortify } if$ } { "The " #4 organization chop.word sortify } if$ } { editor sort.format.names } if$ } FUNCTION {presort} { type$ "book" = type$ "inbook" = or 'author.editor.sort { type$ "proceedings" = 'editor.organization.sort { type$ "manual" = 'author.organization.sort 'author.sort if$ } if$ } if$ " " * year field.or.null sortify * " " * title field.or.null sort.format.title * #1 entry.max$ substring$ 'sort.key$ := } ITERATE {presort} SORT ITERATE {call.type$} ftplugin/ATP_files/atp_RevSearch.py [[[1 34 #!/usr/bin/python # This file is a part of ATP plugin to vim. # AUTHOR: Marcin Szamotulski # SYNTAX: # atp_RevSearch.py # DESRIPTION: # This is a python sctipt which implements reverse searching (okular->vim) # it uses atplib#FindAndOpen() function which finds the vimserver which hosts # the , then opens it on the . # HOW TO CONFIGURE OKULAR to get Reverse Search # Designed to put in okular: # Settings>Configure Okular>Editor # Choose: Custom Text Edit # In the command field type: atp_RevSearch.py '%p' '%l' # If it is not in your $PATH put the full path of the script. # DEBUG: # debug file : /tmp/atp_RevSearch.debug import subprocess, sys output = subprocess.Popen(["vim", "--serverlist"], stdout=subprocess.PIPE) servers = output.stdout.read() server_list = str(servers).splitlines() server = server_list[0] cmd="vim --servername "+server+" --remote-expr \"atplib#FindAndOpen('"+sys.argv[1]+"','"+sys.argv[2]+"')\"" subprocess.call(cmd, shell=True) f = open('/tmp/atp_RevSearch.debug', 'w') f.write(">>> file "+sys.argv[1]+"\n>>> line "+sys.argv[2]+"\n>>> server "+server+"\n>>> server list "+str(server_list)+"\n>>> cmd "+cmd+"\n") f.close() ftplugin/bibsearch_atp.vim [[[1 135 " Vim filetype plugin file " Language: tex " Maintainer: Marcin Szamotulski " Last Change: Mon Jan 03 01:00 2011 C " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " " {{{ Load Once if exists("b:did_ftplugin") | finish | endif let b:did_ftplugin = 1 " }}} " Status Line: function! ATPBibStatus() "{{{ return substitute(expand("%"),"___","","g") endfunction setlocal statusline=%{ATPBibStatus()} " }}} " Maps: " {{{ MAPPINGS if !exists("no_plugin_maps") && !exists("no_atp_bibsearch_maps") map c :call BibChoose() map y :call BibChoose() map p :call BibChoose() map q :hide command! -buffer -nargs=* BibChoose :call BibChoose() endif " }}} " Functions: function! BibChoose(...)" {{{ if a:0 == 0 let which = input("Which entry? ( , or for none) ") else let which = a:1 endif let g:which = which if which == "" return endif if which =~ '^\d*$' let start = stridx(b:ListOfBibKeys[which],'{')+1 let choice = substitute(strpart(b:ListOfBibKeys[which], start), ',\s*$', '', '') let g:choice = choice " Goto right buffer let winbufnr = bufwinnr(b:BufNr) if winbufnr != -1 exe "normal ".winbufnr."w" else if bufexist(b:BufNr) exe "normal buffer ".winbufnr else echohl WarningMsg echo "Buffer was deleted" echohl None return endif endif let LineNr = line(".") let ColNr = col(".") call setline(LineNr, strpart(getline(LineNr), 0, ColNr) . choice . strpart(getline(LineNr), ColNr)) call cursor(LineNr, len(strpart(getline(LineNr), 0, ColNr) . choice)+1) return elseif which =~ '^\d*\(\a\|+\| . "*" .\)$' let letter=substitute(which,'\d','','g') let g:letter = letter let which=substitute(which,'\a\|+\|' . "*",'','g') let start=stridx(b:ListOfBibKeys[which],'{')+1 let choice=substitute(strpart(b:ListOfBibKeys[which], start), ',', '', '') if letter == 'a' let @a=choice elseif letter == 'b' let @b=choice elseif letter == 'c' let @c=choice elseif letter == 'd' let @d=choice elseif letter == 'e' let @e=choice elseif letter == 'f' let @f=choice elseif letter == 'g' let @g=choice elseif letter == 'h' let @h=choice elseif letter == 'i' let @i=choice elseif letter == 'j' let @j=choice elseif letter == 'k' let @k=choice elseif letter == 'l' let @l=choice elseif letter == 'm' let @m=choice elseif letter == 'n' let @n=choice elseif letter == 'o' let @o=choice elseif letter == 'p' let @p=choice elseif letter == 'q' let @q=choice elseif letter == 'r' let @r=choice elseif letter == 's' let @s=choice elseif letter == 't' let @t=choice elseif letter == 'u' let @u=choice elseif letter == 'v' let @v=choice elseif letter == 'w' let @w=choice elseif letter == 'x' let @x=choice elseif letter == 'y' let @y=choice elseif letter == 'z' let @z=choice elseif letter == '*' let @-=choice elseif letter == '+' let @+=choice elseif letter == '-' let @@=choice endif echohl WarningMsg | echomsg "Choice yanekd to the register '" . letter . "'" | echohl None endif endfunction "}}} ftplugin/fd_atp.vim [[[1 77 " Vim filetype plugin file " Language: tex " Maintainer: Marcin Szamotulski " Last Change: 2010 July 9 " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin "{{{ Load Once if exists("b:did_ftplugin") | finish | endif let b:did_ftplugin = 1 "}}} "{{{ OpenFile if !exists("*OpenFile") function! OpenFile() let line = max([line("."), '2'])-2 let file = g:fd_matches[line] " The list of fd files starts at second line. let openbuffer = "topleft split! +setl\\ nospell\\ ft=fd_atp\\ noro " . fnameescape(file) silent exe openbuffer let b:atp_autex=0 endfunction endif "}}} "{{{ ShowFonts function! ShowFonts(fd_file) let font_commands = atplib#ShowFonts(a:fd_file) let message = "" for fcom in font_commands let message .= "\n".fcom endfor let message="Fonts Declared:".message call confirm(message) endfunction "}}} "{{{ Autocommand augroup ATP_fd_list au CursorHold fd_list* :echo get(g:fd_matches, max([line("."),'2'])-2, "") augroup END "}}} "{{{ Preview function! Preview(keep_tex) let keep_tex = ( a:keep_tex == "!" ? 1 : 0 ) let b_pos = getpos("'<")[1] let e_pos = getpos("'>")[1] if getpos("'<") != [0, 0, 0, 0] && getpos("'<") != [0, 0, 0, 0] let fd_files = filter(copy(g:fd_matches),'index(g:fd_matches,v:val)+1 >= b_pos-1 && index(g:fd_matches,v:val)+1 <= e_pos-1') else let fd_files = [g:fd_matches[(max([line("."),'2'])-2)]] endif call atplib#Preview(fd_files, keep_tex) endfunction "}}} "{{{ Commands if bufname("%") =~ 'fd_list' command! -buffer -bang -nargs=? -range Preview :call Preview(, ) command! -buffer ShowFonts :call ShowFonts(g:fd_matches[(max([line("."),'2'])-2)]) map :call OpenFile() map :call ShowFonts(g:fd_matches[(max([line("."),'2'])-2)]) else command! -buffer -nargs=1 Preview :call atplib#Preview(["buffer"],) endif "}}} "{{{ Maps map P :Preview! map p :Preview vmap P :Preview! vmap p :Preview map Q :bd! map q :q!R "}}} ftplugin/plaintex_atp.vim [[[1 7 " Maintainer: Marcin Szamotulski " Note: This file is a part of Automatic Tex Plugin for Vim. " Last Change: " URL: https://launchpad.net/automatictexplugin " b:atp_TexFlavor will be set to plaintex automatically runtime ftplugin/tex_atp.vim ftplugin/tex_atp.vim [[[1 128 " Title: Vim filetype plugin file " Author: Marcin Szamotulski " URL: https://sourceforge.net/projects/atp-vim/ " BUGS: https://lists.sourceforge.net/lists/listinfo/atp-vim-list " " Language: tex " Last Change: Sun Mar 20 05:00 2011 W " GetLatestVimScripts: 2945 61 :AutoInstall: tex_atp.vim " GetLatestVimScripts: 884 1 :AutoInstall: AutoAlign.vim " Copyright Statement: " This file is a part of Automatic Tex Plugin for Vim. " " Automatic Tex Plugin for Vim is free software: you can redistribute it " and/or modify it under the terms of the GNU General Public License as " published by the Free Software Foundation, either version 3 of the " License, or (at your option) any later version. " " Automatic Tex Plugin for Vim is distributed in the hope that it will be " useful, but WITHOUT ANY WARRANTY; without even the implied warranty of " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU " General Public License for more details. " " You should have received a copy of the GNU General Public License along " with Automatic Tex Plugin for Vim. If not, see . " " This licence applies to all files shipped with Automatic Tex Plugin. let b:did_ftplugin = 1 if !exists("g:atp_reload_functions") let g:atp_reload_functions = 0 endif if &cpoptions =~ '<' echohl WarningMsg echo "ATP is removing < from cpoptions" echohl None setl cpoptions-=< endif " Execute the atprc file. " They override cached variables let s:atprc_file = globpath($HOME, '.atprc.vim', 1) " They override cached variables function! ReadATPRC() if filereadable(s:atprc_file) && has("unix") " Note: in $HOME/.atprc file the user can set all the local buffer " variables without using autocommands " " Note: it must be sourced at the begining because some options handle " how atp will load (for example if we load history or not) " It also should be run at the end if the user defines mapping that " should be overwrite the ATP settings (this is done via " autocommand). let path = globpath($HOME, '/.atprc.vim', 1) execute 'source ' . fnameescape(path) else let path = get(split(globpath(&rtp, "**/ftplugin/ATP_files/atprc.vim"), '\n'), 0, "") if path != "" execute 'source ' . fnameescape(path) endif endif endfunction call ReadATPRC() " This is not working: " augroup ATP_atprc " au! VimEnter * :call ReadATPRC() " augroup END " Source Project Script runtime ftplugin/ATP_files/project.vim " Functions needed before setting options. runtime ftplugin/ATP_files/common.vim " Options, global and local variables, autocommands. runtime ftplugin/ATP_files/options.vim " Compilation related stuff. runtime ftplugin/ATP_files/compiler.vim " let compiler_file = findfile('compiler/tex_atp.vim', &rtp) " if compiler_file " execute 'source ' . fnameescape(compiler_file) " endif " LatexBox addons (by D.Munger, with some modifications). if g:atp_LatexBox runtime ftplugin/ATP_files/LatexBox_common.vim runtime ftplugin/ATP_files/LatexBox_complete.vim runtime ftplugin/ATP_files/LatexBox_motion.vim runtime ftplugin/ATP_files/LatexBox_latexmk.vim endif runtime ftplugin/ATP_files/motion.vim runtime ftplugin/ATP_files/search.vim runtime ftplugin/ATP_files/various.vim " Source maps and menu files. runtime ftplugin/ATP_files/mappings.vim if g:atp_LatexBox " LatexBox mappings. runtime ftplugin/ATP_files/LatexBox_mappings.vim endif " Source abbreviations. runtime ftplugin/ATP_files/abbreviations.vim " The menu. runtime ftplugin/ATP_files/menu.vim " Help functions. runtime ftplugin/ATP_files/helpfunctions.vim " Execute the atprc file. " vim:fdm=marker:ff=unix:noet:ts=4:sw=4 ftplugin/bib_atp.vim [[[1 311 " Title: Vim filetype plugin file " Author: Marcin Szamotulski " Email: mszamot [AT] gmail [DOT] com " URL: https://launchpad.net/automatictexplugin " BUG Trucer: https://bugs.launchpad.net/automatictexplugin " Language: bib " Last Change: Sat Mar 12 01:00 2011 W " Copyright Statement: " This file is part of Automatic Tex Plugin for Vim. " " Automatic Tex Plugin for Vim is free software: you can redistribute it " and/or modify it under the terms of the GNU General Public License as " published by the Free Software Foundation, either version 3 of the " License, or (at your option) any later version. " " Automatic Tex Plugin for Vim is distributed in the hope that it will be " useful, but WITHOUT ANY WARRANTY; without even the implied warranty of " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU " General Public License for more details. " " You should have received a copy of the GNU General Public License along " with Automatic Tex Plugin for Vim. If not, see . " " This licence applies to all files shipped with Automatic Tex Plugin. " Variables: " {{{ bib fields if !exists("g:atpbib_pathseparator") if has("win16") || has("win32") || has("win64") || has("win95") let g:atpbib_pathseparator = "\\" else let g:atpbib_pathseparator = "/" endif endif " if !exists("g:atpbib_WgetOutputFile") " let tmpname = tempname() " let g:atpbib_WgetOutputFile = tmpname . g:atpbib_pathseparator . "amsref.html" " endif " if !exists("g:atpbib_wget") " let g:atpbib_wget="wget -O " . g:atpbib_WgetOutputFile " endif if !exists("g:atpbib_WgetOutputFile") let g:atpbib_WgetOutputFile = "amsref.html" endif if !exists("g:atpbib_wget") let g:atpbib_wget="wget" endif if !exists("g:atpbib_Article") let g:atpbib_Article = [ '@article{', \ ' Author = {},', \ ' Title = {},', \ ' Journal = {},', \ ' Year = {},', \ '}' ] endif nmap a :call append(line("."), g:atpbib_Article) if !exists("g:atpbib_Book") let g:atpbib_Book = [ '@book{' , \ ' Author = {},', \ ' Title = {},', \ ' Publisher = {},', \ ' Year = {},', \ '}' ] endif if !exists("g:atpbib_Booklet") let g:atpbib_Booklet = [ '@booklet{' , \ ' Title = {},', \ '}' ] endif if !exists("g:atpbib_Conference") let g:atpbib_Conference = [ '@conference{' , \ ' Author = {},', \ ' Title = {},', \ ' Booktitle = {},', \ ' Publisher = {},', \ ' Year = {},', \ '}' ] endif if !exists("g:atpbib_InBook") let g:atpbib_InBook = [ '@inbook{' , \ ' Author = {},', \ ' Title = {},', \ ' Chapter = {},', \ ' Publisher = {},', \ ' Year = {},', \ '}' ] endif if !exists("g:atpbib_InCollection") let g:atpbib_InCollection = [ '@incollection{' , \ ' Author = {},', \ ' Title = {},', \ ' Booktitle = {},', \ ' Publisher = {},', \ ' Year = {},', \ '}' ] endif if !exists("g:atpbib_InProceedings") let g:atpbib_InProceedings = [ '@inproceedings{' , \ ' Author = {},', \ ' Title = {},', \ ' Booktitle = {},', \ ' Publisher = {},', \ ' Year = {},', \ '}' ] endif if !exists("g:atpbib_Manual") let g:atpbib_Manual = [ '@manual{' , \ ' Title = {},', \ '}' ] endif if !exists("g:atpbib_MastersThesis") let g:atpbib_MastersThesis = [ '@mastersthesis{' , \ ' Author = {},', \ ' Title = {},', \ ' School = {},', \ ' Year = {},', \ '}' ] endif if !exists("g:atpbib_Misc") let g:atpbib_Misc = [ '@misc{', \ ' Title = {},', \ '}' ] endif if !exists("g:atpbib_PhDThesis") let g:atpbib_PhDThesis = [ '@phdthesis{' , \ ' Author = {},', \ ' Title = {},', \ ' School = {},', \ ' Year = {},', \ '}' ] endif if !exists("g:atpbib_Proceedings") let g:atpbib_Proceedings = [ '@proceedings{' , \ ' Title = {},', \ ' Year = {},', \ '}' ] endif if !exists("g:atpbib_TechReport") let g:atpbib_TechReport = [ '@TechReport{' , \ ' Author = {},', \ ' Title = {},', \ ' Institution = {},', \ ' Year = {},', \ '}' ] endif if !exists("g:atpbib_Unpublished") let g:atpbib_Unpublished = [ '@unpublished{', \ ' Author = {},', \ ' Title = {},', \ ' Note = {},', \ '}' ] endif " }}} " AMSRef: " {{{ AMSRef try function! GetAMSRef(what) let what = substitute(a:what, '\s\+', ' ', 'g') let what = substitute(what, '%', '%25', 'g') let what = substitute(what, ',', '%2C', 'g') let what = substitute(what, ':', '%3A', 'g') let what = substitute(what, ';', '%3B', 'g') let what = substitute(what, '/', '%2F', 'g') let what = substitute(what, '?', '%3F', 'g') let what = substitute(what, '+', '%2B', 'g') let what = substitute(what, '=', '%3D', 'g') let what = substitute(what, '#', '%23', 'g') let what = substitute(what, '\$', '%24', 'g') let what = substitute(what, '&', '%26', 'g') let what = substitute(what, '@', '%40', 'g') let what = substitute(what, ' ', '+', 'g') let tmpdir=tempname() call mkdir(tmpdir, "p") let atpbib_WgetOutputFile = tmpdir . g:atpbib_pathseparator . "amsref.html" " Note: Quoting a:what works not as good. let cmd = g:atpbib_wget . " -O " . atpbib_WgetOutputFile . ' "http://www.ams.org/mathscinet-mref?ref='.what.'&dataType=bibtex"' call system(cmd) let loclist = getloclist(0) try exe '1lvimgrep /\CNo Unique Match Found/j ' . fnameescape(atpbib_WgetOutputFile) catch /E480/ endtry if len(getloclist(0)) echohl WarningMsg echomsg "No Unique Match Found" echohl None return [0] endif let pattern = '@\%(article\|book\%(let\)\=\|conference\|inbook\|incollection\|\%(in\)\=proceedings\|manual\|masterthesis\|misc\|phdthesis\|techreport\|unpublished\)\s*{\|^\s*\%(ADDRESS\|ANNOTE\|AUTHOR\|BOOKTITLE\|CHAPTER\|CROSSREF\|EDITION\|EDITOR\|HOWPUBLISHED\|INSTITUTION\|JOURNAL\|KEY\|MONTH\|NOTE\|NUMBER\|ORGANIZATION\|PAGES\|PUBLISHER\|SCHOOL\|SERIES\|TITLE\|TYPE\|VOLUME\|YEAR\|MRCLASS\|MRNUMBER\|MRREVIEWER\)\s*=\s*.*$' try exe 'lvimgrep /'.pattern.'/j ' . fnameescape(atpbib_WgetOutputFile) catch /E480:/ endtry let data = getloclist(0) call setloclist(0, loclist) if !len(data) echohl WarningMsg echomsg "Nothing found." echohl None return [0] endif let type_pattern= '@\%(article\|book\%(let\)\=\|conference\|inbook\|incollection\|\%(in\)\=proceedings\|manual\|masterthesis\|misc\|phdthesis\|techreport\|unpublished\)\>' let bdata = filter(copy(data), "v:val['text'] =~ type_pattern") let blinenumbers = map(copy(bdata), 'v:val["lnum"]') let begin = max(blinenumbers) let linenumbers = map(copy(data), 'v:val["lnum"]') let end = max(linenumbers) let bufnr = bufnr(atpbib_WgetOutputFile) " To use getbufline() buffer must be loaded. It is enough to use :buffer " command because vimgrep loads buffer and then unloads it. execute "buffer " . bufnr let bibdata = getbufline(bufnr, begin, end) execute "bdelete " . bufnr let type = matchstr(bibdata[0], '@\%(article\|book\%(let\)\=\|conference\|inbook\|incollection\|\%(in\)\=proceedings\|manual\|masterthesis\|misc\|phdthesis\|techreport\|unpublished\)\ze\s*\%("\|{\|(\)') " Suggest Key: let bibkey = input("Provide a key (Enter for the AMS bibkey): ") if !empty(bibkey) let bibdata[0] = type . '{' . bibkey . ',' else let bibdata[0] = substitute(matchstr(bibdata[0], '@\w*.*$'), '\(@\w*\)\(\s*\)', '\1', '') endif call add(bibdata, "}") "Go to begin of next entry or end of last entry let line = NEntry('nW') if line == line(".") call EntryEnd("") else call cursor(line(".")-1,1) endif "Append the bibdata: if getline(line('$')) !~ '^\s*$' let bibdata = extend([''], bibdata) endif let bibdata = extend(bibdata, ['']) call append(line('.'), bibdata) let g:atp_bibdata = bibdata call system("rm -rf " . fnamemodify(atpbib_WgetOutputFile, ":h")) return bibdata endfunction catch /E127/ endtry command! -buffer -nargs=1 AMSRef call GetAMSRef() "}}} " JMotion: function! JMotion(flag) " {{{ let pattern = '\%(\%(address\|annote\|author\|booktitle\|chapter\|crossref\|edition\|editor\|howpublished\|institution\|journal\|key\|month\|note\|number\|organization\|pages\|publisher\|school\|series\|title\|type\|volume\|year\|mrclass\|mrnumber\|mrreviewer\)\s*=\s.\zs\|@\w*\%({\|"\|(\|''\)\zs\)' call search(pattern, a:flag) endfunction "}}} " NEntry: function! NEntry(flag,...) "{{{ let keepjumps = ( a:0 >= 1 ? a:1 : "" ) let pattern = '@\%(article\|book\%(let\)\=\|conference\|inbook\|incollection\|\%(in\)\=proceedings\|manual\|masterthesis\|misc\|phdthesis\|techreport\|unpublished\)' " let g:cmd = keepjumps . " call search(".pattern.",".a:flag.")" keepjumps call search(pattern, a:flag) return line(".") endfunction "}}} " EntryEnd: function! EntryEnd(flag) "{{{ call NEntry("bc", "keepjumps") if a:flag =~# 'b' call NEntry("b", "keepjumps") endif keepjumps call search('\%({\|(\|"\|''\)') normal % return line(".") endfunction "}}} " Maps: " {{{ nmap ]] :call NEntry("") nmap } :call NEntry("")zz nmap [[ :call NEntry("b") nmap { :call NEntry("b")zz nmap ][ :call EntryEnd("") nmap [] :call EntryEnd("b") nmap :call JMotion("") nmap :call JMotion("b") imap l:call JMotion("")i imap l:call JMotion("b")i nnoremap :call system("texdoc bibtex") nnoremap a :call append(line("."), g:atpbib_Article):call JMotion("") nnoremap b :call append(line("."), g:atpbib_Book):call JMotion("") nnoremap bo :call append(line("."), g:atpbib_Book):call JMotion("") nnoremap c :call append(line("."), g:atpbib_InProceedings):call JMotion("") nnoremap bl :call append(line("."), g:atpbib_Booklet):call JMotion("") nnoremap ib :call append(line("."), g:atpbib_InBook):call JMotion("") nnoremap ic :call append(line("."), g:atpbib_InCollection):call JMotion("") nnoremap ma :call append(line("."), g:atpbib_Manual):call JMotion("") nnoremap mt :call append(line("."), g:atpbib_MasterThesis):call JMotion("") nnoremap mi :call append(line("."), g:atpbib_Misc):call JMotion("") nnoremap phd :call append(line("."), g:atpbib_PhDThesis):call JMotion("") nnoremap pr :call append(line("."), g:atpbib_Proceedings):call JMotion("") nnoremap tr :call append(line("."), g:atpbib_TechReport):call JMotion("") nnoremap un :call append(line("."), g:atpbib_Unpublished):call JMotion("") " }}} ftplugin/toc_atp.vim [[[1 721 " Vim filetype plugin file " Language: tex " Maintainer: Marcin Szamotulski " Last Change: Sun Feb 27 11:00 2011 W " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " if exists("b:did_ftplugin") | finish | endif let b:did_ftplugin = 1 function! ATP_TOC_StatusLine() " {{{ let l:return = ( expand("%") == "__ToC__" ? "Table of Contents" : 0 ) let l:return = ( expand("%") == "__Labels__" ? "List of Labels" : l:return ) return l:return endfunction setlocal statusline=%{ATP_TOC_StatusLine()} " }}} " {{{ s:getlinenr(...) " a:1 line number to get, if not given the current line " a:2 0/1 0 (default) return linenr as for toc/labels function! Getlinenr(...) let line = a:0 >= 1 ? a:1 : line('.') let labels = a:0 >= 2 ? a:2 : expand("%") == "__Labels__" ? 1 : 0 let g:line = line if labels == 0 return get(b:atp_Toc, line, ["", ""])[1] else return get(b:atp_Labels, line, ["", ""])[1] endif endfunction function! s:getlinenr(...) let line = a:0 >= 1 ? a:1 : line('.') let labels = a:0 >= 2 ? a:2 : expand("%") == "__Labels__" ? 1 : 0 if labels == 0 return get(b:atp_Toc, line, ["", ""])[1] else return get(b:atp_Labels, line, ["", ""])[1] endif endfunction command! -buffer GetLine :echo getlinenr(line(".")) "}}} function! s:getsectionnr(...) "{{{ let line = a:0 == 0 ? getline('.') : getline(a:1) return matchstr(l:line,'^\s*\d\+\s\+\zs\%(\d\|\.\)\+\ze\D') endfunction "}}} " Get the file name and its path from the LABELS/ToC list. function! s:file() "{{{ let labels = expand("%") == "__Labels__" ? 1 : 0 if labels == 0 return get(b:atp_Toc, line("."), ["", ""])[0] else return get(b:atp_Labels, line("."), ["", ""])[0] endif endfunction command! -buffer File :echo s:file() "}}} " {{{1 s:gotowinnr "--------------------------------------------------------------------- " Notes: " (1) choose window with matching buffer name " (2) choose among those which were edited last " Solution: " --N-> choose this window " | " --N-> ----| " | --Y-> choose that window " --go from where you come-->| Does there exist another open window " | with the right buffer name? " | " --Y-> use this window " Does the window have " a correct name? " " This function returns the window number to which we will eventually go. function! s:gotowinnr() let labels_window = expand("%") == "__Labels__" ? 1 : 0 " This is the line number to which we will go. let l:nr=s:getlinenr(line("."), labels_window) " t:atp_bufname " t:atp_winnr were set by TOC(), they should also be set by " autocommands let l:bufname=s:file() if labels_window " Find labels window to go in Labels window if bufwinnr(t:atp_bufname) != -1 let l:gotowinnr=t:atp_winnr else let l:gotowinnr=-1 endif else " Find labels window to go in ToC window if t:atp_bufname == l:bufname " if t:atp_bufname agree with that found in ToC " if the t:atp_winnr is still open if bufwinnr(t:atp_bufname) != -1 let l:gotowinnr=t:atp_winnr else let l:gotowinnr=-1 endif else if bufwinnr("^" . l:bufname . "$") != 0 " if not but there is a window with buffer l:bufname let l:gotowinnr=bufwinnr("^" . l:bufname . "$") else " if not and there is no window with buffer l:bufname let l:gotowinnr=t:atp_winnr endif endif endif return l:gotowinnr endif endfunction command! -buffer GotoWinNr :echo s:gotowinnr() " }}}1 function! GotoLine(closebuffer) "{{{ let labels_window = expand("%") == "__Labels__" ? 1 : 0 " if under help lines do nothing: let toc = getbufline("%",1,"$") let h_line = index(reverse(copy(toc)),'')+1 if line(".") > len(toc)-h_line return '' endif let buf = s:file() " remember the ToC window number let tocbufnr= bufnr("") " line to go to let nr = s:getlinenr(line("."), labels_window) " window to go to let gotowinnr= s:gotowinnr() if gotowinnr != -1 exe gotowinnr . " wincmd w" if fnamemodify(buf, ":p") != fnamemodify(bufname("%"), ":p") exe "e " . fnameescape(buf) endif else exe gotowinnr . " wincmd w" exe "e " . fnameescape(buf) endif "if we were asked to close the window if a:closebuffer == 1 exe "bdelete " . tocbufnr endif "finally, set the position call setpos('.', [0, nr, 1, 0]) exe "normal zt" endfunction " }}} function! yank(arg) " {{{ let labels_window = expand("%") == "__Labels__" ? 1 : 0 let l:toc=getbufline("%",1,"$") let l:h_line=index(reverse(copy(l:toc)),'')+1 if line(".") > len(l:toc)-l:h_line return '' endif let l:cbufnr=bufnr("") let file_name=s:file() if !labels_window if exists("t:atp_labels") || get(t:atp_labels, file_name, "nofile") != "nofile" " set t:atp_labels variable call atplib#generatelabels(getbufvar(s:file(), 'atp_MainFile'), 0) endif let line = s:getlinenr(line("."), labels_window) let choice = get(get(filter(get(deepcopy(t:atp_labels), file_name, []), 'v:val[0] == line'), 0, []), 1 , 'nokey') else if exists("t:atp_labels") || get(t:atp_labels, file_name, "nofile") != "nofile" let line_nr = s:getlinenr(line("."), labels_window) let choice_list = filter(get(deepcopy(t:atp_labels), file_name), "v:val[0] == line_nr" ) " There should be just one element in the choice list " unless there are two labels in the same line. let choice = choice_list[0][1] else let choice = "nokey" endif endif if choice == "nokey" " in TOC, if there is a key we will give it back if not: au! CursorHold __ToC__ echomsg "There is no key." sleep 750m au CursorHold __ToC__ :call EchoLine() return "" else if a:arg == '@' let l:letter=input("To which register? or empty for none ") silent if l:letter == 'a' let @a=choice elseif l:letter == 'b' let @b=choice elseif l:letter == 'c' let @c=choice elseif l:letter == 'd' let @d=choice elseif l:letter == 'e' let @e=choice elseif l:letter == 'f' let @f=choice elseif l:letter == 'g' let @g=choice elseif l:letter == 'h' let @h=choice elseif l:letter == 'i' let @i=choice elseif l:letter == 'j' let @j=choice elseif l:letter == 'k' let @k=choice elseif l:letter == 'l' let @l=choice elseif l:letter == 'm' let @m=choice elseif l:letter == 'n' let @n=choice elseif l:letter == 'o' let @o=choice elseif l:letter == 'p' let @p=choice elseif l:letter == 'q' let @q=choice elseif l:letter == 'r' let @r=choice elseif l:letter == 's' let @s=choice elseif l:letter == 't' let @t=choice elseif l:letter == 'u' let @u=choice elseif l:letter == 'v' let @v=choice elseif l:letter == 'w' let @w=choice elseif l:letter == 'x' let @x=choice elseif l:letter == 'y' let @y=choice elseif l:letter == 'z' let @z=choice elseif l:letter == '*' let @-=choice elseif l:letter == '+' let @+=choice elseif l:letter == '-' let @@=choice endif elseif a:arg == 'p' let l:gotowinnr=s:gotowinnr() exe l:gotowinnr . " wincmd w" " delete the buffer " exe "bdelete " . l:cbufnr " set the line let l:line=getline('.') let l:colpos=getpos('.')[2] if a:arg ==# 'p' let l:bline=strpart(l:line, 0, l:colpos) let l:eline=strpart(l:line, l:colpos) else let l:bline=strpart(l:line, 0, l:colpos-1) let l:eline=strpart(l:line, l:colpos-1) endif call setline('.',l:bline . choice . l:eline) call setpos('.',[getpos('.')[0],getpos('.')[1],getpos('.')[2]+len(choice),getpos('.')[3]]) endif endif endfunction command! -buffer P :call Yank("p") " }}} if !exists("*YankToReg") function! YankToReg() call yank("@") endfunction endif if !exists("*Paste") function! Paste() call yank("p") endfunction endif command! -buffer -nargs=1 Y :call YankToReg() " Show Label Context " {{{1 ShowLabelContext if !exists("*ShowLabelContext") function! ShowLabelContext() let labels_window = expand("%") == "__Labels__" ? 1 : 0 let toc = getbufline("%",1,"$") let h_line = index(reverse(copy(toc)),'')+1 if line(".") > len(toc)-h_line return '' endif let cbuf_name = bufname('%') let buf_name = s:file() let buf_nr = bufnr("^" . buf_name . "$") let win_nr = bufwinnr(buf_name) let g:buf_name = buf_name let g:win_nr = win_nr let line = s:getlinenr(line("."), labels_window) if !exists("t:atp_labels") let t:atp_labels=UpdateLabels(buf_name) endif exe win_nr . " wincmd w" " if win_nr == -1 " exe "e #" . buf_nr " endif exe "split! #" . buf_nr call setpos('.', [0, line, 1, 0]) endfunction endif " }}}1 " Echo line " {{{1 EchoLine if !exists("*EchoLine") function! EchoLine() " If we are not on a toc/label line " return if !s:getlinenr(line(".")) return 0 endif let labels_window = expand("%") == "__Labels__" ? 1 : 0 let toc = getbufline("%",1,"$") let h_line = index(reverse(copy(toc)),'')+1 " if line(".") > len(toc)-h_line " return 0 " endif let buf_name = s:file() let buf_nr = bufnr("^" . buf_name . "$") if !exists("t:atp_labels") let t:atp_labels[buf_name] = UpdateLabels(buf_name)[buf_name] endif let line = s:getlinenr(line("."), labels_window) let sec_line = join(getbufline(buf_name,line)) let g:sec_line = sec_line let sec_type = "" if sec_line =~ '\\subparagraph[^\*]' let sec_type="subparagraph " elseif sec_line =~ '\\subparagraph\*' let sec_type="subparagraph* " elseif sec_line =~ '\\paragraph[^\*]' let sec_type="paragraph " elseif sec_line =~ '\\paragraph\*' let sec_type="paragraph* " elseif sec_line =~ '\\subsubsection[^\*]' let sec_type="subsubsection " elseif sec_line =~ '\\subsubsection\*' let sec_type="subsubsection*" elseif sec_line =~ '\\subsection[^\*]' let sec_type="subsection " elseif sec_line =~ '\\subsection\*' let sec_type="subsection* " elseif sec_line =~ '\\section[^\*]' let sec_type="section " elseif sec_line =~ '\\section\*' let sec_type="section* " elseif sec_line =~ '\\chapter[^\*]' let sec_type="chapter " elseif sec_line =~ '\\chapter\*' let sec_type="chapter* " elseif sec_line =~ '\\part[^\*]' let sec_type="part " elseif sec_line =~ '\\part\*' let sec_type="part* " elseif sec_line =~ '\\bibliography' let sec_type="bibliography " elseif sec_line =~ '\\abstract\|\\begin\s*{\s*abstract\s*}' let sec_type="abstract " elseif sec_line =~ '\\documentclass' let sec_type="preambule " endif let sec_type = toupper(sec_type) if expand("%") == "__Labels__" let sec_type="TYPE " endif let label = matchstr(sec_line,'\\label\s*{\zs[^}]*\ze}') let section = strpart(sec_line,stridx(sec_line,'{')+1,stridx(sec_line,'}')-stridx(sec_line,'{')-1) if section != "" && label != "" echo sec_type . " : '" . section . "'\t label : " . label elseif section != "" echo sec_type . " : '" . section . "'" else echo "" endif return 1 endfunction endif setl updatetime=200 augroup ATP_TOC au CursorHold __ToC__ :call EchoLine() augroup END "}}}1 " Compare Numbers Function {{{1 function! s:CompareNumbers(i1, i2) return str2nr(a:i1) == str2nr(a:i2) ? 0 : str2nr(a:i1) > str2nr(a:i2) ? 1 : -1 endfunction "}}}1 " DeleteSection, PasteSection, SectionStack, Undo " {{{1 " Stack of sections that were removed but not yet paste " each entry is a list [ section title , list of deleted lines, section_nr ] " where the section title is the one from t:atp_toc[filename][2] " section_nr is the section number before deletion " the recent positions are put in the front of the list if expand("%") == "__ToC__" if !exists("t:atp_SectionStack") let t:atp_SectionStack = [] endif function! s:DeleteSection() " if under help lines do nothing: let toc_line = getbufline("%",1,"$") let h_line = index(reverse(copy(toc_line)),'')+1 if line(".") > len(toc_line)-h_line return '' endif let s:deleted_section = toc_line " Get the name and path of the file " to operato on let file_name = s:file() let begin_line = s:getlinenr() let section_nr = s:getsectionnr() let toc = deepcopy(t:atp_toc[file_name]) let type = toc[begin_line][0] " Only some types are supported: if count(['bibliography', 'subsubsection', 'subsection', 'section', 'chapter', 'part'], type) == 0 echo type . " is not supported" sleep 750m return endif " Find the end of the section: " part is ended by part " chapter is ended by part or chapter " section is ended by part or chapter or section " and so on, " bibliography is ended by like subsubsection. if type == 'part' let type_pattern = 'part\|bibliography' elseif type == 'chapter' let type_pattern = 'chapter\|part\|bibliography' elseif type == 'section' let type_pattern = '\%(sub\)\@ str2nr(begin_line)') let end_line = -1 let bibliography = 0 for line in sort(keys(toc), "s:CompareNumbers") if toc[line][0] =~ type_pattern let end_line = line-1 if toc[line][0] =~ 'bibliography' let bibliography = 1 endif break endif endfor if end_line == -1 && &l:filetype == "plaintex" echomsg "ATP can not delete last section in plain tex files :/" sleep 750m return endif " Window to go to let gotowinnr = s:gotowinnr() if gotowinnr != -1 exe gotowinnr . " wincmd w" else exe gotowinnr . " wincmd w" exe "e " . fnameescape(file_name) endif "finally, set the position call setpos('.',[0,begin_line,1,0]) normal! V if end_line != -1 && !bibliography call setpos('.',[0, end_line, 1, 0]) elseif bibliography call setpos('.',[0, end_line, 1, 0]) let end_line = search('^\s*$', 'cbnW')-1 elseif end_line == -1 let end_line = search('\ze\\end\s*{\s*document\s*}') normal! ge endif " and delete normal d let deleted_section = split(@*, '\n') if deleted_section[0] !~ '^\s*$' call extend(deleted_section, [' '], 0) endif " Update the Table of Contents call remove(t:atp_toc[file_name], begin_line) let new_toc={} for line in keys(t:atp_toc[file_name]) if str2nr(line) < str2nr(begin_line) call extend(new_toc, { line : t:atp_toc[file_name][line] }) else call extend(new_toc, { line-len(deleted_section) : t:atp_toc[file_name][line] }) endif endfor let t:atp_toc[file_name] = new_toc " Being still in the tex file make backup: if exists("g:atp_SectionBackup") call extend(g:atp_SectionBackup, [[title, type, deleted_section, section_nr, expand("%:p")]], 0) else let g:atp_SectionBackup = [[title, type, deleted_section, section_nr, expand("%:p")]] endif " return to toc TOC 0 " Update the stack of deleted sections call extend(t:atp_SectionStack, [[title, type, deleted_section, section_nr]],0) endfunction command! -buffer DeleteSection :call DeleteSection() " nnoremap dd :call DeleteSection() " Paste the section from the stack " just before where the next section starts. " type = p/P like paste p/P. " a:1 - the number of the section in the stack (from 1,...) " - by default it is the last one. function! s:PasteSection(type, ...) let stack_number = a:0 >= 1 ? a:1-1 : 0 let g:stack_number = stack_number if !len(t:atp_SectionStack) sleep 750m echomsg "The stack of deleted sections is empty" return endif let buffer = s:file() " if a:after if a:type ==# "P" || line(".") == 1 let g:debug =1 let g:line = line(".") let begin_line = s:getlinenr((line("."))) else let g:debug =2 let g:line = line(".")+1 let begin_line = s:getlinenr((line(".")+1)) if begin_line == "" let begin_line = "last_line" endif endif let g:begin_line = begin_line " Window to go to let gotowinnr = s:gotowinnr() if gotowinnr != -1 exe gotowinnr . " wincmd w" else exe gotowinnr . " wincmd w" exe "e " . fnameescape(buffer) endif if begin_line != "" if begin_line != "last_line" call setpos(".", begin_line-1) else keepjumps call setpos(".", [0, line("$"), 1, 0]) keepjumps exe "normal $" keepjumps call search('\n.*\\end\s*{\s*document\s*}', 'bW') let begin_line = line(".") let g:linenr = line(".") endif elseif &l:filetype != 'plaintex' keepjumps let begin_line = search('\\end\s*{\s*document\s*}', 'nw') else echo "Pasting at the end is not supported for plain tex documents" return endif let number = len(t:atp_SectionStack)-1 " Append the section call append(begin_line-1, t:atp_SectionStack[stack_number][2]) " Set the cursor position to the begining of moved section and add it to " the jump list call setpos(".", [0, begin_line, 1, 0]) " Regenerate the Table of Contents: TOC! " Update the stack call remove(t:atp_SectionStack, stack_number) endfunction command! -buffer -nargs=? PasteSection :call PasteSection('p', ) " Lists title of sections in the t:atp_SectionStack function! s:SectionStack() if len(t:atp_SectionStack) == 0 echomsg "Section stack is empty" sleep 750m return endif let i = 1 echo "Stack Number/Type/Title" let msg = [] for section in t:atp_SectionStack call add(msg, i . "/" . section[1] . " " . section[3] . "/" . section[0]) let i+=1 endfor call input(join(msg + [ "Press " ] , "\n")) endfunction command! -buffer SectionStack :call SectionStack() " Undo in the winnr under the cursor. " a:1 is one off u or U, default is u. function! s:Undo(...) let cmd = ( a:0 >= 1 && a:1 =~ '\cu\|g\%(-\|+\)' ? a:1 : 'u' ) let winnr = s:gotowinnr() exe winnr . " wincmd w" exe "normal! " . cmd TOC endfunction command! -buffer -nargs=? Undo :call Undo() nnoremap u :call Undo('u') nnoremap U :call Undo('U') nnoremap g- :call Undo('g-') nnoremap g+ :call Undo('g+') endif " }}}1 function! Help() " {{{1 " Note: here they are not well indented, but in the output they are :) echo "Available Mappings:" echo "q close ToC window" echo " go to and close" echo " go to" echo "c or y yank the label to a register" echo "p or P yank and paste the label (in the source file)" echo "e echo the title to command line" if expand("%") == "__ToC__" echo ":DeleteSection Delete section under the cursor" echo ":PasteSection [] Paste section from section stack" echo ":SectionStack Show section stack" echo ":Undo Undo" endif echo " this help message" endfunction function! s:CursorLine() "{{{1 if s:getlinenr(line(".")) && !&l:cursorline setl cursorline elseif !s:getlinenr(line(".")) && &l:cursorline setl nocursorline endif endfunction augroup ATP_CursorLine au CursorMoved,CursorMovedI __ToC__ call s:CursorLine() augroup END " MAPPINGS {{{1 if !exists("no_plugin_maps") && !exists("no_atp_toc_maps") map q :bdelete map :call GotoLine(1) map :call GotoLine(0) " This does not work: " noremap :call GotoLine(0) " when the cursor is in another buffer (and the option mousefocuse is not " set) it calles the command instead of the function, I could add a check if " mouse is over the right buffer. With mousefocuse it also do not works very " well. map c :call YankToReg() map y :call YankToReg() map p :call Paste() map P :call yank("P") map s :call ShowLabelContext() map e :call EchoLine() map :call Help() endif autoload/atplib.vim [[[1 4485 " Title: Vim library for ATP filetype plugin. " Author: Marcin Szamotulski " Email: mszamot [AT] gmail [DOT] com " Note: This file is a part of Automatic Tex Plugin for Vim. " URL: https://launchpad.net/automatictexplugin " Language: tex " Table: function! atplib#Table(list,spaces) " {{{ " take a list of lists and make a list which is nicly formated (to echo it) " spaces = list of spaces between columns. "maximal length of columns: let max_list=[] let new_list=[] for i in range(len(a:list[0])) let max=max(map(deepcopy(a:list), "len(v:val[i])")) call add(max_list, max) endfor for row in a:list let new_row=[] let i=0 for el in row let new_el=el.join(map(range(max([0,max_list[i]-len(el)+get(a:spaces,i,0)])), "' '"), "") call add(new_row, new_el) let i+=1 endfor call add(new_list, new_row) endfor return map(new_list, "join(v:val, '')") endfunction "}}} " Outdir: append to '/' to b:atp_OutDir if it is not present. function! atplib#outdir() "{{{1 if has("win16") || has("win32") || has("win64") || has("win95") if b:atp_OutDir !~ "\/$" let b:atp_OutDir=b:atp_OutDir . "\\" endif else if b:atp_OutDir !~ "\/$" let b:atp_OutDir=b:atp_OutDir . "/" endif endif return b:atp_OutDir endfunction "}}}1 " Return {path} relative to {rel}, if not under {rel} return {path} function! atplib#RelativePath(path, rel) "{{{1 let current_dir = getcwd() exe "lcd " . fnameescape(a:rel) let rel_path = fnamemodify(a:path, ':.') exe "lcd " . fnameescape(current_dir) return rel_path endfunction "}}}1 " Return fullpath function! atplib#FullPath(file_name) "{{{1 let cwd = getcwd() if a:file_name =~ '^\s*\/' let file_path = a:file_name else exe "lcd " . fnameescape(b:atp_ProjectDir) let file_path = fnamemodify(a:file_name, ":p") exe "lcd " . fnameescape(cwd) endif return file_path endfunction "}}}1 " Toggle On/Off Completion " {{{1 atplib#OnOffComp function! atplib#OnOffComp(ArgLead, CmdLine, CursorPos) return filter(['on', 'off'], 'v:val =~ "^" . a:ArgLead') endfunction "}}}1 " Open Function: "{{{1 atplib#Open " a:1 - pattern or a file name " a:1 is regarded as a filename if filereadable(pattern) is non " zero. function! atplib#Open(bang, dir, TypeDict, ...) if a:dir == "0" echohl WarningMsg echomsg "You have to set g:atp_LibraryPath in your vimrc or atprc file." echohl Normal return endif let pattern = ( a:0 >= 1 ? a:1 : "") let file = filereadable(pattern) ? pattern : "" if file == "" if a:bang == "!" || !exists("g:atp_Library") let g:atp_Library = filter(split(globpath(a:dir, "*"), "\n"), 'count(keys(a:TypeDict), fnamemodify(v:val, ":e"))') let found = deepcopy(g:atp_Library) else let found = deepcopy(g:atp_Library) endif call filter(found, "fnamemodify(v:val, ':t') =~ pattern") " Resolve symlinks: call map(found, "resolve(v:val)") " Remove double entries: call filter(found, "count(found, v:val) == 1") if len(found) > 1 echohl Title echo "Found files:" echohl Normal let i = 1 for file in found if len(map(copy(found), "v:val =~ escape(fnamemodify(file, ':t'), '~') . '$'")) == 1 echo i . ") " . fnamemodify(file, ":t") else echo i . ") " . pathshorten(fnamemodify(file, ":p")) endif let i+=1 endfor let choice = input("Which file to open? ")-1 if choice == -1 return endif let file = found[choice] elseif len(found) == 1 let file = found[0] else echohl WarningMsg echomsg "Nothing found." echohl None return endif endif let ext = fnamemodify(file, ":e") let viewer = get(a:TypeDict, ext, 0) if viewer == '0' echomsg "\n" echomsg "Filetype: " . ext . " is not supported, add an entry to g:atp_OpenTypeDict" return endif if viewer !~ '^\s*cat\s*$' && viewer !~ '^\s*g\=vim\s*$' && viewer !~ '^\s*edit\s*$' && viewer !~ '^\s*tabe\s*$' && viewer !~ '^\s*split\s*$' call system(viewer . " '" . file . "' &") elseif viewer =~ '^\s*g\=vim\s*$' || viewer =~ '^\s*tabe\s*$' exe "tabe " . fnameescape(file) setl nospell elseif viewer =~ '^\s*edit\s*$' || viewer =~ '^\s*split\s*$' exe viewer . " " . fnameescape(file) setl nospell elseif viewer == '^\s*cat\s*' redraw! echohl Title echo "cat '" . file . "'" echohl Normal echo system(viewer . " '" . file . "' &") endif " if fnamemodify(file, ":t") != "" && count(g:atp_open_completion, fnamemodify(file, ":t")) == 0 " call extend(g:atp_open_completion, [fnamemodify(file, ":t")], 0) " endif " This removes the hit Enter vim prompt. call feedkeys("") return endfunction "}}}1 " Find Vim Server: find server 'hosting' a file and move to the line. " {{{1 atplib#FindAndOpen " Can be used to sync gvim with okular. " just set in okular: " settings>okular settings>Editor " Editor Custom Text Editor " Command gvim --servername GVIM --remote-expr "atplib#FindAndOpen('%f','%l')" " You can also use this with vim but you should start vim with " vim --servername VIM " and use servername VIM in the Command above. function! atplib#ServerListOfFiles() redir! > /tmp/atpvim_ServerListOfFiles.debug let file_list = [] for nr in range(1, bufnr('$')-1) let files = getbufvar(nr, "ListOfFiles") let main_file = getbufvar(nr, "atp_MainFile") if string(files) != "" call add(file_list, main_file) endif if string(main_file) != "" call extend(file_list, files) endif endfor call filter(file_list, 'v:val != ""') call map(file_list, "fnamemodify(v:val, ':p')") redir end return file_list endfunction function! atplib#FindAndOpen(file, line) let file = ( fnamemodify(a:file, ":e") == "tex" ? a:file : fnamemodify(a:file, ":p:r") . ".tex" ) let server_list = split(serverlist(), "\n") redir! > /tmp/atpvim_FindAndOpen.debug echo "server list=".string(server_list) if len(server_list) == 0 retun 1 endif let use_server = "no_server" for server in server_list let file_list=split(remote_expr(server, 'atplib#ServerListOfFiles()'), "\n") echo "server " .server . " " . string(file_list) if index(file_list, file) != -1 let use_server = server break endif endfor if use_server == "no_server" let use_server=server_list[0] endif call system("gvim --servername " . use_server . " --remote-wait +" . a:line . " " . fnameescape(file) . " &") echo "file:".file." line:".a:line. " server name:".use_server." hitch-hiking server:".v:servername redir end return "File:".file." line:".a:line. " server name:".use_server." Hitch-hiking server:".v:servername endfunction "}}}1 " Labels Tools: GrepAuxFile, SrotLabels, generatelabels and showlabes. " {{{1 LABELS " the argument should be: resolved full path to the file: " resove(fnamemodify(bufname("%"),":p")) " {{{2 --------------- atplib#GrepAuxFile silent! function! atplib#GrepAuxFile(...) " Aux file to read: let atp_MainFile = atplib#FullPath(b:atp_MainFile) let aux_filename = a:0 == 0 ? fnamemodify(atp_MainFile, ":r") . ".aux" : a:1 if !filereadable(aux_filename) " We should worn the user that there is no aux file " /this is not visible ! only after using the command 'mes'/ echohl WarningMsg echomsg "There is no aux file. Run ".b:atp_TexCompiler." first." echohl Normal return [] " CALL BACK is not working " I can not get output of: vim --servername v:servername --remote-expr v:servername " for v:servername " Here we should run latex to produce auxfile " echomsg "Running " . b:atp_TexCompiler . " to get aux file." " let labels = system(b:atp_TexCompiler . " -interaction nonstopmode " . atp_MainFile . " 1&>/dev/null 2>1 ; " . " vim --servername ".v:servername." --remote-expr 'atplib#GrepAuxFile()'") " return labels endif " let aux_file = readfile(aux_filename) let saved_llist = getloclist(0) if bufloaded(aux_filename) exe "silent! bd! " . bufnr(aux_filename) endif try silent execute 'lvimgrep /\\newlabel\s*{/j ' . fnameescape(aux_filename) catch /E480:/ endtry let loc_list = getloclist(0) call setloclist(0, saved_llist) call map(loc_list, ' v:val["text"]') let labels = [] if g:atp_debugGAF let g:gaf_debug = {} endif " Equation counter depedns on the option \numberwithin{equation}{section} " /now this only supports article class. let equation = len(atplib#GrepPreambule('^\s*\\numberwithin{\s*equation\s*}{\s*section\s*}')) let g:equation = equation " for line in aux_file for line in loc_list " if line =~ '^\\newlabel' " line is of the form: " \newlabel{