" Vimball Archiver by Charles E. Campbell, Jr., Ph.D. UseVimball finish ftplugin/ATP_files/LatexBox_common.vim [[[1 317 " 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 Apr 30 07: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 "[ATP:] ".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 && !g:atp_reload_functions 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 '[ATP:] 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 "[ATP:] 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") && !g:atp_reload_functions 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 || g:atp_reload_functions " 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(bline, len(line(bline))) " 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 || g:atp_reload_functions " 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 "[LatexBox:] latexmk exited with status " . a:status else echomsg "[LatexBox:] 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 "[LatexBox:] 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 "[LatexBox:] 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 "[LatexBox:] 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 "[LatexBox:] 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 752 " 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_ProjectGlobalVariable = [ " \ 'b:atp_MainFile', " \ 'b:atp_ProjectScript', " \ 'b:atp_LocalCommands', 'b:atp_LocalEnvironments', " \ 'b:atp_LocalColors', " \ 'b:TreeOfFiles', 'b:ListOfFiles', " \ 'b:TypeDict', 'b:LevelDict', " \ 'b:atp_StarEnvDefault', 'b:atp_StarMathEnvDefault', " \ ] " 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_ProjectGlobalVariables = ['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 exe "redir! > ".g:atp_TempDir."/LoadScript.log" let hist_time = reltime() 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 "[ATP:] 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:] 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:] ATP_ProjectScript: sourcing " . a:project_script endif catch /E484:/ endtry if g:atp_debugProject echomsg "[ATP:] 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 "[ATP:] 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 "[ATP:] 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 )) ) exe "redir! > ".g:atp_TempDir."/LoadProjectScript.log" 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 "Load Project Script 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 exe "redir! > ".g:atp_TempDir."/WriteProjectScript.log" 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 "Write Project Script 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 "Write Project Script 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 "Write Project Script 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 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 {var} = {lvar} 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_ProjectGlobalVariables 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 "Write Project Script time = " . reltimestr(reltime(time)) . "\n" endif if g:atp_debugProject let g:return = 3 endif if g:atp_debugProject >= 2 echomsg "Write Project Script 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 "Write Project Script 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 "Write Project Script time = " . reltimestr(reltime(time)) redir END endif if g:atp_debugProject >= 2 echomsg "Write Project Script 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_ProjectLocalVariables : g:atp_ProjectGlobalVariables ) if type == 'local' echomsg "[ATP:] 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_ProjectLocalVariables, 'local') au BufWrite *.tex call s:WriteProjectScript("", s:common_project_script, g:atp_ProjectGlobalVariables, '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 "[ATP:] Project Script - ON." else echomsg "[ATP:] Project Script - 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 "[ATP:] Project Script ".file." deleted." if type == "local" && a:bang == "!" let file = s:common_project_script call delete(file) echo "[ATP:] Project Script ".file." deleted." endif if file == s:common_project_script for var in g:atp_ProjectGlobalVariables 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 852 " 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 " {{{ Variables if !exists("g:askfortheoutdir") || g:atp_reload_variables 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_variables 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_variables 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_variables 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: " b:atp_PackageList is not used " 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') 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 " \ && ( !exists("t:atp_QuickFixOpen") || exists("t:atp_QuickFixOpen") && !t:atp_QuickFixOpen ) 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' return [ {}, [], {}, {} ] endif let run_nr = a:0 >= 3 ? a:3 : 1 let biblatex = 0 " Adjust g:atp_inputfile_pattern if it is not set right if run_nr == 1 let pattern = '^[^%]*\\\(input\s*{\=\|include\s*{' if '\subfile{' !~ g:atp_inputfile_pattern && atplib#SearchPackage('subfiles') let pattern .= '\|subfiles\s*{' endif let biblatex = atplib#SearchPackage('biblatex') if biblatex " If biblatex is present, search for bibliography files only in the " preambule. if '\addbibresource' =~ g:atp_inputfile_pattern || '\addglobalbib' =~ g:atp_inputfile_pattern || '\addsectionbib' =~ g:atp_inputfile_pattern || '\bibliography' =~ g:atp_inputfile_pattern echo "[ATP:] You might remove biblatex patterns from g:atp_inputfile_pattern if you use biblatex package." endif let biblatex_pattern = '^[^%]*\\\%(bibliography\s*{\|addbibresource\s*\%(\[[^]]*\]\)\?\s*{\|addglobalbib\s*\%(\[[^]]*\]\)\?\s*{\|addsectionbib\s*\%(\[[^]]*\]\)\?\s*{\)' else let pattern .= '\|bibliography\s*{' endif let pattern .= '\)' endif let pattern = a:0 >= 1 ? a:1 : g:atp_inputfile_pattern if g:atp_debugToF if exists("g:atp_TempDir") if run_nr == 1 exe "redir! > ".g:atp_TempDir."/TreeOfFiles.log" else exe "redir! >> ".g:atp_TempDir."/TreeOfFiles.log" endif 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) call setloclist(0,[]) if biblatex try silent execute 'lvimgrep /'.biblatex_pattern.'\%<'.end_preamb.'l/j ' . fnameescape(a:main_file) catch /E480:/ endtry endif else let end_preamb = 0 call setloclist(0,[]) endif try silent execute "lvimgrepadd /".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) let g:loclist1 = loclist 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 iname == "" && biblatex let iname = substitute(matchstr(line, biblatex_pattern . '\(''\|"\)\=\zs\f\%(\f\|\s\)*\ze\1\='), '\s*$', '', '') endif if g:atp_debugToF silent echo run_nr . ") iname=".iname endif if line =~ '{\s*' . iname let iname = substitute(iname, '\\\@\|\\addglobalbib\>\|\\addsectionbib\>\|\\addbibresource\>\)' let type = "bib" elseif lnum < end_preamb && run_nr == 1 let type = "preambule" else let type = "input" endif if g:atp_debugToF silent echo run_nr . ") type=" . type endif let inames = [] if type != "bib" let inames = [ atplib#append_ext(iname, '.tex') ] else let inames = map(split(iname, ','), "atplib#append_ext(v:val, '.bib')") endif if g:atp_debugToF silent echo run_nr . ") inames " . string(inames) endif " Find the full path only if it is not already given. for iname in inames let saved_iname = iname if iname != fnamemodify(iname, ":p") if type != "bib" let iname = atplib#KpsewhichFindFile('tex', iname, b:atp_OutDir . "," . g:atp_texinputs , 1, ':p', '^\%(\/home\|\.\)', '\(^\/usr\|texlive\|kpsewhich\|generic\|miktex\)') else let iname = atplib#KpsewhichFindFile('bib', iname, b:atp_OutDir . "," . g:atp_bibinputs , 1, ':p') endif endif if fnamemodify(iname, ":t") == "" let iname = expand(saved_iname, ":p") endif if g:atp_debugToF silent echo run_nr . ") iname " . string(iname) endif if g:atp_RelativePath let iname = atplib#RelativePath(iname, (fnamemodify(resolve(b:atp_MainFile), ":h"))) endif call add(ifiles, [ iname, lnum] ) call add(list, iname) call extend(type_dict, { iname : type } ) call extend(level_dict, { iname : run_nr } ) endfor endfor if g:atp_debugToF silent echo run_nr . ") list=".string(list) endif " Be recursive if: flat is off, file is of input type. if !flat || flat <= -1 for [ifile, line] in ifiles if type_dict[ifile] == "input" && flat <= 0 || ( type_dict[ifile] == "preambule" && flat <= -1 ) let [ ntree, nlist, ntype_dict, nlevel_dict ] = TreeOfFiles(ifile, pattern, flat, run_nr+1) call extend(tree, { ifile : [ ntree, line ] } ) call extend(list, nlist, index(list, ifile)+1) call extend(type_dict, ntype_dict) call extend(level_dict, nlevel_dict) endif endfor else " Make the flat tree for [ ifile, line ] in ifiles call extend(tree, { ifile : [ {}, line ] }) endfor endif " Showing time takes ~ 0.013sec. " if run_nr == 1 " echomsg "TIME:" . join(reltime(time), ".") . " main_file:" . a:main_file " endif let [ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ] = deepcopy([ tree, list, type_dict, level_dict]) " restore current working directory if run_nr == 1 exe "lcd " . fnameescape(cwd) endif if g:atp_debugToF && run_nr == 1 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! LatexRunning() " python << EOL " import psutil, vim " if vim.eval("exists('b:atp_LastLatexPID')"): " lpid = int(vim.eval("exists('b:atp_LastLatexPID') ? b:atp_LastLatexPID : -1")) " if lpid != -1: " try: " name=psutil.Process(lpid).name " except psutil.NoSuchProcess: " lpid=0 " vim.command(":let b:atp_LastLatexPID="+str(lpid)) " else: " vim.command(":let b:atp_LastLatexPID=0") " EOL " endfunction function! ATPRunning() "{{{ if !g:atp_statusNotif " Do not put any message if user dosn't want it. return "" endif if g:atp_Compiler == "python" " For python compiler for var in [ "Latex", "Bibtex", "Python" ] if !exists("b:atp_".var."PIDs") let b:atp_{var}PIDs = [] endif call atplib#PIDsRunning("b:atp_".var."PIDs") endfor if len(b:atp_LatexPIDs) > 0 let atp_running= len(b:atp_LatexPIDs) elseif len(b:atp_BibtexPIDs) > 0 let atp_running= len(b:atp_BibtexPIDs) else return '' endif else " for g:atp_Compiler='bash' let atp_running=b:atp_running 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 atp_running >= 2 return atp_running." ".Compiler elseif atp_running >= 1 return Compiler else return "" endif endif " For g:atp_Compiler='python' if exists("g:atp_callback") && g:atp_callback if exists("b:atp_LatexPIDs") && len(b:atp_LatexPIDs)>0 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 exists("b:atp_ProgressBar") && b:atp_ProgressBar != {} let max = max(values(b:atp_ProgressBar)) let progress_bar="[".max."]".( g:atp_statusOutDir ? " " : "" ) else let progress_bar="" endif if atp_running >= 2 return atp_running." ".Compiler." ".progress_bar elseif atp_running >= 1 return Compiler." ".progress_bar else return "" endif elseif exists("b:atp_BibtexPIDs") && len(b:atp_BibtexPIDs)>0 return b:atp_BibCompiler elseif exists("b:atp_MakeindexPIDs") && len(b:atp_MakeindexPIDs)>0 return "makeindex" 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) "{{{ if expand("%") == "[Command Line]" || &l:filetype == "qf" " If one uses q/ or q? this status function should not be used. return endif 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_variables if &filetype == 'plaintex' let g:atp_inputfile_pattern = '^[^%]*\\input\>\s*' else if atplib#SearchPackage("subfiles") let g:atp_inputfile_pattern = '^[^%]*\\\(input\s*{\=\|include\s*{\|subfile\s*{' else let g:atp_inputfile_pattern = '^[^%]*\\\(input\s*{\=\|include\s*{' endif if atplib#SearchPackage("biblatex") let g:atp_inputfile_pattern .= '\)' else let g:atp_inputfile_pattern .= '\|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 VimEnter *.tex :call s:SetNotificationColor() 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 1675 " 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. " Note: compile.py script has hardcoded the same value. let s:runlimit = 9 try compiler tex catch E666: endtry " }}} " 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 = join((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 = join((exists("b:atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") ? getbufvar(bufnr("%"), "atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") : []), " ") " Follow the symbolic link let link=resolve(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) : "" ) if g:atp_debugV let g:global_options = global_options let g:local_options = local_options let g:sync_args = sync_args let g:viewer = viewer endif 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) if b:atp_Viewer == "xpdf" call system(view_cmd) else call system(view_cmd) redraw! endif else echomsg "[ATP:] output file do not exists. Calling " . b:atp_TexCompiler if fwd_search if g:atp_Compiler == 'python' call PythonCompiler( 0, 2, 1, 'silent' , "AU" , atp_MainFile, "") else call Compiler( 0, 2, 1, 'silent' , "AU" , atp_MainFile, "") endif else if g:atp_Compiler == 'python' call PythonCompiler( 0, 1, 1, 'silent' , "AU" , atp_MainFile, "") else call Compiler( 0, 1, 1, 'silent' , "AU" , atp_MainFile, "") endif endif endif endfunction noremap ATP_ViewOutput :call ViewOutput() "}}} " Forward Search " {{{ GetSyncData function! GetSyncData(line, col) if !filereadable(fnamemodify(atplib#FullPath(b:atp_MainFile), ":r").'.synctex.gz') redraw! echomsg "[SyncTex:] calling ".get(g:CompilerMsg_Dict, b:atp_TexCompiler, b:atp_TexCompiler)." to generate synctex data. Wait a moment..." let cmd=b:atp_TexCompiler . " -synctex=1 " . shellescape(atplib#FullPath(b:atp_MainFile)) call system(cmd) 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'" " SyncTex is fragile for the file name: if it is file name or full path, it " must agree literally with what is written in .synctex.gz file " first we try with full path then with file name without path. let synctex_output=split(system(synctex_cmd), "\n") if get(synctex_output, 1, '') =~ '^SyncTex Warning: No tag for' " Write better test (above) let synctex_cmd="synctex view -i ".a:line.":".a:col.":'".b:atp_MainFile. "' -o '".fnamemodify(b:atp_MainFile, ":r").".pdf'" let synctex_output=split(system(synctex_cmd), "\n") " call add(g:debug,get(synctex_output, 1, '')) if get(synctex_output, 1, '') =~ '^SyncTex Warning:' return [ "no_sync", get(synctex_output, 1, ''), 0 ] endif endif if g:atp_debugSync let g:synctex_cmd=synctex_cmd let g:synctex_output=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=get(y_coord_list, 0, "no sync data") let y_coord= ( y_coord != "no sync data" ? matchstr(y_coord, 'y:\zs[0-9.]*') : y_coord ) let x_coord_list=copy(synctex_output) call filter(x_coord_list, "v:val =~ '^\\cx:\\d\\+'") let x_coord=get(x_coord_list, 0, "no sync data") let x_coord= ( x_coord != "no sync data" ? matchstr(x_coord, 'x:\zs[0-9.]*') : x_coord ) if g:atp_debugSync let g:page=page let g:y_coord=y_coord let g:x_coord=x_coord endif if page == "no_sync" return [ "no_sync", "No SyncTex Data: try on another line (or recompile the document).", 0 ] endif let page_nr=matchstr(page, '^\cPage:\zs\d\+') let [ b:atp_synctex_pagenr, b:atp_synctex_ycoord, b:atp_synctex_xcoord ] = [ page_nr, y_coord, x_coord ] return [ page_nr, y_coord, x_coord ] endfunction function! SyncShow( page_nr, y_coord) if a:y_coord < 300 let height="top" elseif a:y_coord < 500 let height="middle" else let height="bottom" endif if a:page_nr != "no_sync" echomsg "[SyncTex:] ".height." of page ".a:page_nr else echohl WarningMsg echomsg "[SyncTex:] ".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, ...) "{{{ if g:atp_debugSyncTex exe "redir! > ".g:atp_TempDir."/SyncTex.log" endif let output_check = ( a:0 >= 1 && a:1 == 0 ? 0 : 1 ) let dryrun = ( a:0 >= 2 && a:2 == 1 ? 1 : 0 ) " Mouse click is mapped to ... => thus it first changes " the cursor position. let [ line, col ] = [ line("."), col(".") ] 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 if g:atp_debugSyncTex silent echo "ViewOutput sync" redir END endif return 2 endif if b:atp_Viewer == "xpdf" let [ page_nr, y_coord, x_coord ] = GetSyncData(line, col) let sync_cmd_page = "xpdf -remote " . shellescape(b:atp_XpdfServer) . " -exec 'gotoPage(".page_nr.")'" let sync_cmd_y = "xpdf -remote " . shellescape(b:atp_XpdfServer) . " -exec 'scrollDown(".y_coord.")'" let sync_cmd_x = "xpdf -remote " . shellescape(b:atp_XpdfServer) . " -exec 'scrollRight(".x_coord.")'" "There is a bug in xpdf. We need to sleep between sending commands to it.: let sleep = ( g:atp_XpdfSleepTime ? 'sleep '.string(g:atp_XpdfSleepTime).'s;' : '' ) let sync_cmd = "(".sync_cmd_page.";".sleep.sync_cmd_y.";".sleep.sync_cmd_x.")&" if !dryrun call system(sync_cmd) call SyncShow(page_nr, y_coord) endif if g:atp_debugSyncTex silent echo "sync_cmd=".sync_cmd endif elseif b:atp_Viewer == "okular" let [ page_nr, y_coord, x_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) call SyncShow(page_nr, y_coord) endif if g:atp_debugSyncTex silent echo "sync_cmd=".sync_cmd 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") ? " ".join(g:atp_xdviOptions, " ") : " " ) ." ".join(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 if g:atp_debugSyncTex silent echo "sync_cmd=".sync_cmd endif else let sync_cmd="" if g:atp_debugSyncTex silent echo "sync_cmd=EMPTY" endif endif if g:atp_debugSyncTex redir END endif return 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 " The same but using python (it is not used) " TODO: end this. function! PythonGetPID() python << EOF import psutil latex = vim.eval("b:atp_TexCompiler") # Make dictionary: xpdf_servername : file # to test if the server host file use: # basename(xpdf_server_file_dict().get(server, ['_no_file_'])[0]) == basename(file) ps_list=psutil.get_pid_list() latex_running = False for pr in ps_list: try: name=psutil.Process(pr).name cmdline=psutil.Process(pr).cmdline if name == latex: latex_pid=pr latex_running=True break except psutil.NoSuchProcess: pass if latex_running: vim.command("let s:var="+str(latex_pid)) else: vim.command("let s:var=''") EOF endfunction function! GetPID() if g:atp_Compiler == "bash" let s:var=s:getpid() if s:var != "" echomsg "[ATP:] ".b:atp_TexCompiler . " pid(s): " . s:var else let b:atp_running = 0 echomsg "[ATP:] ".b:atp_TexCompiler . " is not running" endif else call atplib#PIDsRunning("b:atp_LatexPIDs") if len(b:atp_LatexPIDs) > 0 echomsg "[ATP:] ".b:atp_TexCompiler . " pid(s): " . join(b:atp_LatexPIDs, ", ") else let b:atp_LastLatexPID = 0 echomsg "[ATP:] ".b:atp_TexCompiler . " is not running" endif endif 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 "}}} "{{{ GetSid, SidWrap 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 "}}} " }}} " This function is called to run TeX compiler and friends as many times as necessary. " Makes references and bibliographies (supports bibtex), indexes. "{{{ MakeLatex " Function Arguments: function! MakeLatex(bang, verbose, start) " a:verbose and a:bang are not yet used by makelatex.py let PythonMakeLatexPath = globpath(&rtp, "ftplugin/ATP_files/makelatex.py") let interaction = ( a:verbose=="verbose" ? b:atp_VerboseLatexInteractionMode : 'nonstopmode' ) let tex_options = shellescape(b:atp_TexOptions.',-interaction='.interaction) let ext = get(g:atp_CompilersDict, matchstr(b:atp_TexCompiler, '^\s*\zs\S\+\ze'), ".pdf") let ext = substitute(ext, '\.', '', '') let global_options = join((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 = join((exists("b:atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") ? getbufvar(bufnr("%"), "atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") : []), ";") if global_options != "" let viewer_options = global_options.";".local_options else let viewer_options = local_options endif let reload_viewer = ( index(g:atp_ReloadViewers, b:atp_Viewer)+1 ? ' --reload-viewer ' : '' ) let reload_on_error = ( b:atp_ReloadOnError ? ' --reload-on-error ' : '' ) let bibliographies = join(keys(filter(copy(b:TypeDict), "v:val == 'bib'")), ',') let cmd=g:atp_Python." ".PythonMakeLatexPath. \ " --texfile ".shellescape(atplib#FullPath(b:atp_MainFile)). \ " --start ".a:start. \ " --output-format ".ext. \ " --cmd ".b:atp_TexCompiler. \ " --bibcmd ".b:atp_BibCompiler. \ " --bibliographies ".shellescape(bibliographies). \ " --outdir ".b:atp_OutDir. \ " --keep ". shellescape(join(g:keep, ',')). \ " --tex-options ".tex_options. \ " --servername ".v:servername. \ " --viewer ".shellescape(b:atp_Viewer). \ " --xpdf-server ".b:atp_XpdfServer. \ " --viewer-options ".shellescape(viewer_options). \ " --progname ".v:progname. \ " --tempdir ".shellescape(g:atp_TempDir). \ (t:atp_DebugMode=='verbose'||a:verbose=='verbose'?' --env ""': " --env ".shellescape(b:atp_TexCompilerVariable)). \ reload_viewer . reload_on_error unlockvar g:atp_TexCommand let g:atp_TexCommand=cmd lockvar g:atp_TexCommand " Write file let backup = &backup let writebackup = &writebackup " Disable WriteProjectScript let eventignore = &l:eventignore setl eventignore+=BufWrite silent! w let &l:eventignore = eventignore if a:verbose == "verbose" exe ":!".cmd elseif has("win16") || has("win32") || has("win64") let output=system(cmd) else let output=system(cmd." &") endif endfunction "}}} " This function kills all running latex processes. " a slightly better approach would be to kill compile.py scripts "{{{ KillAll " the argument is a list of pids " a:1 if present supresses a message. function! KillPIDs(pids,...) if len(a:pids) == 0 && a:0 == 0 return endif python << END import os, signal from signal import SIGKILL pids=vim.eval("a:pids") for pid in pids: try: os.kill(int(pid),SIGKILL) except OSError, e: if e.errno == 3: # No such process error. pass else: raise END endfunction function! Kill(bang) if !has("python") if a:bang != "!" echohl WarningMsg echomsg "[ATP:] you need python suppor" echohl Normal endif return endif if len(b:atp_PythonPIDs) call KillPIDs(b:atp_PythonPIDs) endif if len(b:atp_LatexPIDs) call KillPIDs(b:atp_LatexPIDs) endif endfunction "}}} function! SetBiberSettings() if b:atp_BibCompiler !~# '^\s*biber\>' return elseif !exists("s:biber_keep_done") let s:biber_keep_done = 1 if index(g:keep, "run.xml") == -1 g:keep += [ "run.xml" ] endif if index(g:keep, "bcf") == -1 g:keep += [ "bcf" ] endif endif endfunction " THE MAIN COMPILER FUNCTIONs: " {{{ s:PythonCompiler function! PythonCompiler(bibtex, start, runs, verbose, command, filename, bang) " Set biber setting on the fly call SetBiberSettings() if !has('gui') && a:verbose == 'verbose' && len(b:atp_LatexPIDs) > 0 redraw! echomsg "[ATP:] please wait until compilation stops." return " This is not working: (I should kill compile.py scripts) echomsg "[ATP:] killing all instances of ".get(g:CompilerMsg_Dict,b:atp_TexCompiler,'TeX') call KillPIDs(b:atp_LatexPIDs,1) sleep 1 PID endif " Debug varibles " On Unix the output of compile.py run by this function is available at " g:atp_TempDir/compiler.py.log if g:atp_debugPythonCompiler let g:debugPC_bibtex =a:bibtex let g:debugPC_start =a:start let g:debugPC_runs =a:runs let g:debugPC_verbose =a:verbose let g:debugPC_command =a:command let g:debugPC_filename =a:filename let g:debugPC_bang =a:bang endif if !exists("t:atp_DebugMode") let t:atp_DebugMode = g:atp_DefaultDebugMode endif if t:atp_DebugMode != 'verbose' && a:verbose != 'verbose' let b:atp_LastLatexPID = -1 endif 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 "[ATP:] 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 if !has('clientserver') if has("win16") || has("win32") || has("win64") || has("win95") echohl WarningMsg echomsg "[ATP:] ATP needs +clientserver vim compilation option." echohl Normal else echohl WarningMsg echomsg "[ATP:] python compiler needs +clientserver vim compilation option." echomsg " falling back to g:atp_Compiler=\"bash\"" echohl Normal let g:atp_Compiler = "bash" return endif endif " Set options for compile.py let interaction = ( a:verbose=="verbose" ? b:atp_VerboseLatexInteractionMode : 'nonstopmode' ) let tex_options = b:atp_TexOptions.',-interaction='.interaction " let g:tex_options=tex_options let ext = get(g:atp_CompilersDict, matchstr(b:atp_TexCompiler, '^\s*\zs\S\+\ze'), ".pdf") let ext = substitute(ext, '\.', '', '') let global_options = join((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 = join(( exists("atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") ? getbufvar(bufnr("%"), "atp_".matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')."Options") : []), ";") if global_options != "" let viewer_options = global_options.";".local_options else let viewer_options = local_options endif let bang = ( a:bang == '!' ? ' --bang ' : '' ) let bibtex = ( a:bibtex ? ' --bibtex ' : '' ) let reload_on_error = ( b:atp_ReloadOnError ? ' --reload-on-error ' : '' ) let gui_running = ( has("gui_running") ? ' --gui-running ' : '' ) let reload_viewer = ( index(g:atp_ReloadViewers, b:atp_Viewer)+1 ? ' --reload-viewer ' : '' ) let aucommand = ( a:command == "AU" ? ' --aucommand ' : '' ) let no_progress_bar = ( g:atp_ProgressBar ? '' : ' --no-progress-bar ' ) let bibliographies = join(keys(filter(copy(b:TypeDict), "v:val == 'bib'")), ',') let autex_wait = ( b:atp_autex_wait ? ' --autex_wait ' : '') " Set the command let cmd=g:atp_Python." ".g:atp_PythonCompilerPath." --command ".b:atp_TexCompiler \ ." --tex-options ".shellescape(tex_options) \ ." --verbose ".a:verbose \ ." --file ".shellescape(atplib#FullPath(a:filename)) \ ." --output-format ".ext \ ." --runs ".a:runs \ ." --servername ".v:servername \ ." --start ".a:start \ ." --viewer ".shellescape(b:atp_Viewer) \ ." --xpdf-server ".shellescape(b:atp_XpdfServer) \ ." --viewer-options ".shellescape(viewer_options) \ ." --keep ". shellescape(join(g:keep, ',')) \ ." --progname ".v:progname \ ." --bibcommand ".b:atp_BibCompiler \ ." --bibliographies ".shellescape(bibliographies) \ ." --logdir ".shellescape(g:atp_TempDir) \ .(t:atp_DebugMode=='verbose'||a:verbose=='verbose'?' --env ""': " --env ".shellescape(b:atp_TexCompilerVariable)) \ . bang . bibtex . reload_viewer . reload_on_error . gui_running . aucommand . no_progress_bar \ . autex_wait " Write file let backup=&backup let writebackup=&writebackup if a:command == "AU" if &backup | setlocal nobackup | endif if &writebackup | setlocal nowritebackup | endif endif " Disable WriteProjectScript let eventignore = &l:eventignore setl eventignore+=BufWrite silent! w let &l:eventignore = eventignore if a:command == "AU" let &l:backup = backup let &l:writebackup = writebackup endif unlockvar g:atp_TexCommand let g:atp_TexCommand = cmd lockvar g:atp_TexCommand " Call compile.py let b:atp_running += ( a:verbose != "verbose" ? 1 : 0 ) if a:verbose == "verbose" exe ":!".cmd elseif g:atp_debugPythonCompiler && has("unix") call system(cmd." 2".g:atp_TempDir."/PythonCompiler.log &") elseif has("win16") || has("win32") || has("win64") call system(cmd) else call system(cmd." &") endif endfunction " }}} " {{{ 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) " Set biber setting on the fly call SetBiberSettings() if !has('gui') && a:verbose == 'verbose' && b:atp_running > 0 redraw! echomsg "[ATP:] please wait until compilation stops." return endif if g:atp_debugCompiler exe "redir! > ".g:atp_TempDir."/Compiler.log" 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 !exists("t:atp_DebugMode") let t:atp_DebugMode = g:atp_DefaultDebugMode endif 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 "[ATP:] 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_TempDir . matchstr(tempname(), '\/\w\+\/\d\+') let tmpfile=atplib#append(tmpdir, "/") . fnamemodify(a:filename,":t:r") if g:atp_debugCompiler let g:tmpdir=tmpdir let g:tmpfile=tmpfile silent echo "tmpdir=".tmpdir silent echo "tmpfile=".tmpfile endif call system("mkdir -m 0700 -p ".shellescape(tmpdir)) " if exists("*mkdir") " call mkdir(tmpdir, "p", 0700) " else " echoerr "[ATP:] Your vim doesn't have mkdir function, please try the python compiler." " return " 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 outbbl = b:atp_OutDir . fnamemodify(basename,":t:r") . ".bbl" let tmpaux = fnamemodify(tmpfile, ":r") . ".aux" let tmpbbl = fnamemodify(tmpfile, ":r") . ".bbl" 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"') 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 let reload_viewer = ( index(g:atp_ReloadViewers, b:atp_Viewer) == '-1' ? ' --reload-viewer ' : '' ) if b:atp_Viewer =~ '^\s*xpdf\>' && reload_viewer 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 call xpdfpid() " I could use here XpdPid(), the reason to not use it is that " then there is a way to run ATP without python. if s: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. " the name of this variable is not missleading ... 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 = v:progname . " --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") ? join(g:atp_xpdfOptions, " ") : "" )." ".(exists("b:xpdfOptions") ? join(getbufvar(0, "atp_xpdfOptions"), " ") : " ") let start = b:atp_Viewer . " -remote " . shellescape(b:atp_XpdfServer) . " " . xpdf_options . " & " else let start = "" endif " SET THE COMMAND let interaction = ( a:verbose=="verbose" ? b:atp_VerboseLatexInteractionMode : 'nonstopmode' ) let variable = ( a:verbose!="verbose" ? substitute(b:atp_TexCompilerVariable, ';', ' ', 'g') : '' ) let comp = variable . " " . b:atp_TexCompiler . " " . substitute(b:atp_TexOptions, ',', ' ','g') . " -interaction=" . interaction . " -output-directory=" . shellescape(tmpdir) . " " . shellescape(a:filename) let vcomp = variable . " " . b:atp_TexCompiler . " " . substitute(b:atp_TexOptions, ',', ' ','g') . " -interaction=". interaction . " -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(fnamemodify(outaux, ":t")) . "; ".g:atp_cpcmd." ".shellescape(outbbl)." ".shellescape(tmpbbl).";" . comp . " 1>/dev/null 2>&1 " else let texcomp=comp.";clear;".g:atp_cpcmd." ".shellescape(tmpaux)." ".shellescape(outaux)."; bibtex ".shellescape(fnamemodify(outaux, ":t")).";".g:atp_cpcmd." ".shellescape(outbbl)." ".shellescape(tmpbbl)."; ".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_cmd = v:progname . ' --servername ' . v:servername . ' --remote-expr ' . \ shellescape('atplib#TexReturnCode') . '\($?\) ; ' 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 = v:progname . ' --servername ' . v:servername . ' --remote-expr ' . \ shellescape('atplib#CallBack').'\(\"'.a:verbose.'\",\"'.a:command.'\",\"'.a:bibtex.'\"\)'. " ; " 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 silent! 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' " "cd ".shellescape(tmpdir).";". 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(...) if mode()=='i' && g:atp_updatetime_insert == 0 || \ mode()=='n' && g:atp_updatetime_normal == 0 return "autex is off for the mode: ".mode()." (see :help mode())" endif " Wait if the compiler is running. The problem is that CursorHoldI autocommands " are not triggered more than once after 'updatetime'. " echomsg "***" " echomsg "b:atp_autex_wait=".b:atp_autex_wait " echomsg "mode=".mode() if index(split(g:atp_autex_wait, ','), mode()) != -1 " \ !b:atp_autex_wait if g:atp_Compiler == "python" call atplib#PIDsRunning("b:atp_PythonPIDs") echomsg string(b:atp_PythonPIDs) else call atplib#PIDsRunning("b:atp_LatexPIDs") endif call atplib#PIDsRunning("b:atp_BibtexPIDs") echo string(b:atp_BibtexPIDs) if g:atp_Compiler == "python" && len(b:atp_PythonPIDs) || \ g:atp_Compiler == "bash" && len(b:atp_LatexPIDs) || \ len(b:atp_BibtexPIDs) " unlockvar b:atp_autex_wait " let b:atp_autex_wait=1 " lockvar b:atp_autex_wait return endif " else " unlockvar b:atp_autex_wait " let b:atp_autex_wait=0 " lockvar b:atp_autex_wait endif " 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 !exists("b:atp_changedtick") " let b:atp_changedtick = b:changedtick " endif if g:atp_Compare == "changedtick" let cond = ( b:changedtick != b:atp_changedtick ) else let cond = ( compare(readfile(expand("%"))) ) endif let g:cond=cond 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() if g:atp_Compiler == 'python' call PythonCompiler(0, 0, b:atp_auruns, mode, "AU", atp_MainFile, "") else call Compiler(0, 0, b:atp_auruns, mode, "AU", atp_MainFile, "") endif 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 if g:atp_Compiler == 'python' call PythonCompiler(0, 0, b:atp_auruns, mode, "AU", atp_MainFile, "") else call Compiler(0, 0, b:atp_auruns, mode, "AU", atp_MainFile, "") endif redraw return "compile for the first time" endif return "files does not differ" endfunction " function! ATP_auTeX() " call auTeX() " endfunction " This is set by SetProjectName (options.vim) where it should not! augroup ATP_auTeX au! au CursorHold *.tex call s:auTeX() au CursorHoldI *.tex call s:auTeX() 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) if !exists("t:atp_DebugMode") let t:atp_DebugMode = g:atp_DefaultDebugMode endif if a:0 >= 1 let mode = ( a:1 != 'default' ? a:1 : t:atp_DebugMode ) else let mode = t:atp_DebugMode endif if mode =~# '^s\%[ilent]$' let mode = 'silent' elseif mode =~# '^d\%[ebug]$' let mode = 'debug' elseif mode =~# 'D\%[ebug]$' let mode = 'Debug' elseif mode =~# '^v\%[erbose]$' let mode = 'verbose' else let mode = t:atp_DebugMode 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 echo "[ATP:] ".Compiler . " will run " . a:1 . " times." elseif a:runs == 2 echo "[ATP:] ".Compiler . " will run twice." elseif a:runs == 1 echo "[ATP:] ".Compiler . " will run once." elseif a:runs > 5 echo "[ATP:] ".Compiler . " will run " . s:runlimit . " times." endif endif if g:atp_Compiler == 'python' call PythonCompiler(0,0, a:runs, mode, "COM", atp_MainFile, a:bang) else call Compiler(0,0, a:runs, mode, "COM", atp_MainFile, a:bang) endif 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_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 = b:atp_BibCompiler." " let atp_MainFile = atplib#FullPath(b:atp_MainFile) if b:atp_BibCompiler =~ '^\s*biber\>' let file = fnamemodify(resolve(atp_MainFile),":t:r") else let file = fnamemodify(resolve(atp_MainFile),":t:r") . ".aux" endif 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(file) let b:atp_BibtexOutput=system(command) let b:atp_BibtexReturnCode=v:shell_error echo b:atp_BibtexOutput else echo "[ATP:] aux file " . auxfile . " not readable." endif exe "lcd " . fnameescape(saved_cwd) endfunction nnoremap SimpleBibtex :call SimpleBibtex() function! Bibtex(bang, ...) if a:0 >= 1 && a:1 =~# '^o\%[utput]$' redraw! if exists("b:atp_BibtexReturnCode") echo "[Bib:] BibTeX returned with exit code " . b:atp_BibtexReturnCode endif if exists("b:atp_BibtexOutput") echo substitute(b:atp_BibtexOutput, '\(^\zs\|\n\)', '\1 ', "g") else echo "No BibiTeX output." endif return elseif a:bang == "" call SimpleBibtex() return endif let atp_MainFile = atplib#FullPath(b:atp_MainFile) let g:a=a:0 if a:0 >= 1 let mode = ( a:1 != 'default' ? a:1 : t:atp_DebugMode ) else let mode = t:atp_DebugMode endif if mode =~# '^s\%[ilent]$' let mode = 'silent' elseif mode =~# '^d\%[ebug]$' let mode = 'debug' elseif mode =~# 'D\%[ebug]$' let mode = 'Debug' elseif mode =~# '^v\%[erbose]$' let mode = 'verbose' else let mode = t:atp_DebugMode endif if g:atp_Compiler == 'python' call PythonCompiler(1, 0, 0, mode, "COM", atp_MainFile, "") else call Compiler(1, 0, 0, mode, "COM", atp_MainFile, "") endif endfunction function! BibtexComp(A,L,P) return "silent\ndebug\nDebug\nverbose\noutput" endfunction nnoremap SimpleBibtex :call Bibtex("") nnoremap BibtexDefault :call Bibtex("!", "default") nnoremap BibtexSilent :call Bibtex("!", "silent") nnoremap Bibtexdebug :call Bibtex("!", "debug") 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(...) let l:cgetfile = ( a:0 >=2 ? a:2 : 0 ) " This l:cgetfile == 1 only if run by the command :ErrorFormat if l:cgetfile == 1 && a:1 == '' echo "[ATP:] current error format: ".getbufvar(bufnr(fnamemodify(&l:errorfile, ":r").".tex"), "atp_ErrorFormat") return endif let carg_raw = ( a:0 == 0 ? g:atp_DefaultErrorFormat : a:1 ) let carg_list= split(carg_raw, '\zs') if carg_list[0] =~ '^[+-]$' let add=remove(carg_list,0) else let add=0 endif for i in range(0, len(carg_list)-2) if carg_list[i] == 'f' && get(carg_list,i+1, "") == "i" call remove(carg_list, i+1) let carg_list[i]="fi" endif endfor " Get the bufnr of tex file corresponding to the &l:errorfile let bufnr = bufnr(fnamemodify(&l:errorfile, ":r").".tex") let carg = !exists("w:quickfix_title") && exists("b:atp_ErrorFormat") \ ? b:atp_ErrorFormat \ : getbufvar((bufnr), "atp_ErrorFormat") let atp_ErrorFormat = ( exists("b:atp_ErrorFormat") ? b:atp_ErrorFormat : getbufvar((bufnr), "atp_ErrorFormat") ) if carg_raw =~ '^+' for flag in carg_list if flag != 'f' && atp_ErrorFormat !~ flag || flag == 'f' && atp_ErrorFormat !~ 'fi\@!' let carg .= flag endif endfor elseif carg_raw =~ '^-' for flag in carg_list if flag != 'f' let carg=substitute(carg, flag, '', 'g') else let carg=substitute(carg, 'fi\@!', '', 'g') endif endfor else let carg=carg_raw endif let b:atp_ErrorFormat = carg if exists("w:quickfix_title") call setbufvar(bufnr, "atp_ErrorFormat", carg) endif let &l:errorformat="" if ( carg =~ 'e' || carg =~# 'all' ) 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 ( carg =~ 'w' || carg =~# 'all' ) 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 ( carg =~ '\Cc' || carg =~# 'all' ) " 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 ( carg =~ '\Cr' || carg =~# 'all' ) 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 carg =~ '\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 carg =~ '\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 carg =~ '\CF' if &l:errorformat == "" let &l:errorformat = 'File: %m' else let &l:errorformat = &l:errorformat . ',File: %m' endif endif if carg =~ '\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 carg =~ '\CA\cll' let l:dont_ignore = 1 let pm = '+' endif 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 if l:cgetfile try cgetfile catch E40: endtry endif if t:atp_QuickFixOpen let winnr=winnr() " Quickfix is opened, jump to it and change the size copen exe "resize ".min([atplib#qflength(), g:atp_DebugModeQuickFixHeight]) exe winnr."wincmd w" endif if add != "0" echo "[ATP:] current error format: ".b:atp_ErrorFormat endif endfunction "}}} "{{{ 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(...) " It is not because it is run from atplib#CallBack() 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 echo "[ATP:] no error file: " . errorfile echohl Normal return endif let log=readfile(errorfile) let nr=1 for line in log if line =~ "LaTeX Warning:" && log[nr] !~ "^$" let newline=line . log[nr] let log[nr-1]=newline call remove(log,nr) endif let nr+=1 endfor call writefile(log, errorfile) " set errorformat let l:arg = ( a:0 >= 1 ? a:1 : b:atp_ErrorFormat ) if l:arg =~ 'o' OpenLog return elseif l:arg =~ 'b' echo b:atp_BibtexOutput return endif call s:SetErrorFormat(l:arg) let show_message = ( a:0 >= 2 ? a:2 : 1 ) " read the log file cg " final stuff if len(getqflist()) == 0 if show_message echo "[ATP:] no errors :)" endif return ":)" else cl return 1 endif endfunction "}}} if !exists("*ListErrorsFlags") function! ListErrorsFlags(A,L,P) return "all\nAll\nc\ne\nF\nf\nfi\no\nr\nw\nb" endfunction endif if !exists("*ListErrorsFlags_A") function! ListErrorsFlags_A(A,L,P) " This has no o flag. return "all\nAll\nc\ne\nF\nf\nfi\nr\nw\nb" endfunction endif "}}} " function! SetErrorFormat(efm) " " if a:efm == "" " return " endif " " unlockvar b:atp_ErrorFormat " let b:atp_ErrorFormat = a:efm " cgetfile " " endfunction endif "}}} " Commands And Autocommands: " {{{ command! -buffer -bang Kill :call Kill() command! -buffer -nargs=? ViewOutput :call ViewOutput() command! -buffer SyncTex :call SyncTex(0) command! -buffer PID :call GetPID() command! -buffer -bang MakeLatex :call SetBiberSettings() | call MakeLatex(, 'silent', 0) nmap ATP_MakeLatex :MakeLatex command! -buffer -nargs=? -bang -count=1 -complete=custom,DebugComp TEX :call TeX(, , ) command! -buffer -count=1 DTEX :call TeX(, , 'debug') command! -buffer -bang -nargs=? -complete=custom,BibtexComp Bibtex :call Bibtex(, ) command! -buffer -nargs=? -complete=custom,ListErrorsFlags_A SetErrorFormat :call SetErrorFormat(,1) augroup ATP_QuickFix_1 au! au FileType qf command! -buffer -nargs=? -complete=custom,ListErrorsFlags_A SetErrorFormat :call SetErrorFormat(,1) au FileType qf command! -buffer -nargs=? -complete=custom,ListErrorsFlags_A ErrorFormat :call SetErrorFormat(,1) au FileType qf command! -buffer -nargs=? -complete=custom,ListErrorsFlags_A ShowErrors :call SetErrorFormat() augroup END command! -buffer -nargs=? -complete=custom,ListErrorsFlags_A ErrorFormat :call SetErrorFormat(,1) let load_ef=(exists("t:atp_QuickFixOpen") ? !t:atp_QuickFixOpen : 1) " Note: the following code works nicly with :split (do not reloads the log file) but " this is not working with :edit " but one can use: au BufEnter *.tex :cgetfile if exists("t:atp_QuickFixOpen") && t:atp_QuickFixOpen " If QuickFix is opened: let load_ef = 0 else let load_ef = 1 endif " let g:load_ef=load_ef call SetErrorFormat(g:atp_DefaultErrorFormat, load_ef) 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 543 " 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: " maps is a list of list of the form: " [ "map", "map_args", "mapleader", "lhs", "rhs", "varname", "help msg" ] " define = 1/0 1 if map is to be defined (this is a place for a variable name, to turn " maps on/off on the fly) Note that this must be variable name not a value! " for example " [ "inoremap", "", "#a", "\\alpha", 1, "\\alpha" ] " Fucntions used to define maps. " Commands to library functions (autoload/atplib.vim) " in insert mode doesn't trigger InsertLeave autocommands " this fixes this. if g:atp_MapCC imap endif if has("gui") cmap \_s\+ else cmap \_s\+ endif cmap \_s\+ 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 ' ], " \ ] " MAPS: " 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 ) " They are interfering with vim GG. exe "nmap ".g:atp_goto_section_leader."S :keepjumps exe v:count1.\"SSec\"" exe "nmap ".g:atp_goto_section_leader."s :keepjumps exe v:count1.\"Sec\"" exe "nmap ".g:atp_goto_section_leader."c :keepjumps exe v:count1.\"Chap\"" exe "nmap ".g:atp_goto_section_leader."p :keepjumps exe v:count1.\"Part\"" if g:atp_MapCommentLines nmap c CommentLines vmap c CommentLines nmap u UnCommentLines vmap u UnCommentLines endif nmap t SyncTexKeyStroke nmap SyncTexMouse 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_forward_motion_leader."E JumptoNextEnvironment" " map GotoNextEnvironment execute "map ".g:atp_map_backward_motion_leader."e GotoPreviousEnvironment" execute "map ".g:atp_map_backward_motion_leader."E JumptoPreviousEnvironment" " map GotoPreviousEnvironment 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=b:atp_StarMathEnvDefault} \\end{equation=b:atp_StarMathEnvDefault} 0 1" execute "vnoremap ".g:atp_vmap_environment_leader."A :WrapSelection \\begin{align=b:atp_StarMathEnvDefault} \\end{align=b: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."< :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_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 " exe "vmap ".g:atp_MapSelectComment." vSelectComment" exe "map ".g:atp_MapSelectComment." vvSelectComment" " Normal mode maps (mostly) if mapcheck('v') == "" nmap v ATP_ViewOutput endif " nmap ToggleSpace nmap q/:call ATP_CmdwinToggleSpace(1)i if mapcheck('Q/', 'n') == "" nmap Q/ q/:call ATP_CmdwinToggleSpace(1) endif if mapcheck('Q?', 'n') == "" nmap Q? q?:call ATP_CmdwinToggleSpace(1) endif if mapcheck('s') == "" nmap s ToggleStar endif nmap d ToggledebugMode nmap D ToggleDebugMode vmap WrapEnvironment 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 nmap D ATP_TeXDebug " nmap ATP_MakeLatex "ToDo: imaps! nmap ATP_TeXVerbose nmap ToggleAuTeX imap ToggleAuTeXa nmap ` ToggleTab imap ` ToggleTab nmap ' ToggleMathIMaps imap ' ToggleMathIMapsa nmap B SimpleBibtex nmap b BibtexDefault nmap d Delete imap d Delete nmap l OpenLog imap l OpenLog nnoremap :ShowErrors e inoremap :ShowErrors e noremap e :ShowErrors nnoremap e :ShowErrors e inoremap e :ShowErrors e nnoremap w :ShowErrors w inoremap w :ShowErrors w nnoremap r :ShowErrors rc inoremap r :ShowErrors rc nnoremap f :ShowErrors f inoremap f :ShowErrors f nnoremap g PdfFonts nnoremap :TexDoc inoremap :TexDoc " 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{}' if !exists("g:atp_imap_define_fonts") let g:atp_imap_define_fonts = 1 endif if !exists("g:atp_imap_fonts") || g:atp_reload_variables let g:atp_imap_fonts = [ \ [ 'inoremap', ' ', g:atp_imap_second_leader, 'rm', ':call Insert("\\textrm{", "\\mathrm{")a', "g:atp_imap_define_fonts", 'rm font'], \ [ 'inoremap', ' ', g:atp_imap_second_leader, 'up', '\textup{}', "g:atp_imap_define_fonts", 'up font'], \ [ 'inoremap', ' ', g:atp_imap_second_leader, 'md', '\textmd{}', "g:atp_imap_define_fonts", 'md font'], \ [ 'inoremap', ' ', g:atp_imap_second_leader, 'it', ':call Insert("\\textit{", "\\mathit{")a', "g:atp_imap_define_fonts", 'it font'], \ [ 'inoremap', ' ', g:atp_imap_second_leader, 'sl', '\textsl{}', "g:atp_imap_define_fonts", 'sl font'], \ [ 'inoremap', ' ', g:atp_imap_second_leader, 'sc', '\textsc{}', "g:atp_imap_define_fonts", 'sc font'], \ [ 'inoremap', ' ', g:atp_imap_second_leader, 'sf', ':call Insert("\\textsf{", "\\mathsf{")a', "g:atp_imap_define_fonts", 'sf font'], \ [ 'inoremap', ' ', g:atp_imap_second_leader, 'bf', ':call Insert("\\textbf{", "\\mathbf{")a', "g:atp_imap_define_fonts", 'bf font'], \ [ 'inoremap', ' ', g:atp_imap_second_leader, 'tt', ':call Insert("\\texttt{", "\\mathtt{")a', "g:atp_imap_define_fonts", 'tt font'], \ [ 'inoremap', ' ', g:atp_imap_second_leader, 'em', '\emph{}', "g:atp_imap_define_fonts", 'emphasize font'], \ [ 'inoremap', ' ', g:atp_imap_second_leader, 'no', ':call Insert("\\textnormal{", "\\mathnormal{")a', "g:atp_imap_define_fonts", 'normal font'], \ [ 'inoremap', ' ', g:atp_imap_second_leader, 'bb', '\mathbb{}', "g:atp_imap_define_fonts", 'mathbb font'], \ [ 'inoremap', ' ', g:atp_imap_second_leader, 'cal', '\mathcal{}', "g:atp_imap_define_fonts", 'mathcal font'], \ ] endif call atplib#MakeMaps(g:atp_imap_fonts) " GREEK LETTERS if !exists("g:atp_imap_greek_letters") || g:atp_reload_variables let g:atp_imap_greek_letters= [ \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'a', '\alpha', "g:atp_imap_define_greek_letters", '\alpha' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'b', '\beta', "g:atp_imap_define_greek_letters", '\beta' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'c', '\chi', "g:atp_imap_define_greek_letters", '\chi' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'd', '\delta', "g:atp_imap_define_greek_letters", '\delta' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'e', '\epsilon', "g:atp_imap_define_greek_letters", '\epsilon' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'v', '\varepsilon', "g:atp_imap_define_greek_letters", '\varepsilon' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'f', '\phi', "g:atp_imap_define_greek_letters", '\phi' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'y', '\psi', "g:atp_imap_define_greek_letters", '\psi' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'g', '\gamma', "g:atp_imap_define_greek_letters", '\gamma' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'h', '\eta', "g:atp_imap_define_greek_letters", '\eta' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'k', '\kappa', "g:atp_imap_define_greek_letters", '\kappa' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'l', '\lambda', "g:atp_imap_define_greek_letters", '\lambda' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'i', '\iota', "g:atp_imap_define_greek_letters", '\iota' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'm', '\mu', "g:atp_imap_define_greek_letters", '\mu' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'n', '\nu', "g:atp_imap_define_greek_letters", '\nu' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'p', '\pi', "g:atp_imap_define_greek_letters", '\pi' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'o', '\theta', "g:atp_imap_define_greek_letters", '\theta' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'r', '\rho', "g:atp_imap_define_greek_letters", '\rho' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 's', '\sigma', "g:atp_imap_define_greek_letters", '\sigma' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 't', '\tau', "g:atp_imap_define_greek_letters", '\tau' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'u', '\upsilon', "g:atp_imap_define_greek_letters", '\upsilon' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'v', '\varsigma', "g:atp_imap_define_greek_letters", '\varsigma' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'v', '\vartheta', "g:atp_imap_define_greek_letters", '\vartheta' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'w', '\omega', "g:atp_imap_define_greek_letters", '\omega' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'x', '\xi', "g:atp_imap_define_greek_letters", '\xi' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'z', '\zeta', "g:atp_imap_define_greek_letters", '\zeta' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'D', '\Delta', "g:atp_imap_define_greek_letters", '\Delta' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'Y', '\Psi', "g:atp_imap_define_greek_letters", '\Psi' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'F', '\Phi', "g:atp_imap_define_greek_letters", '\Phi' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'G', '\Gamma', "g:atp_imap_define_greek_letters", '\Gamma' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'L', '\Lambda', "g:atp_imap_define_greek_letters", '\Lambda' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'M', '\Mu', "g:atp_imap_define_greek_letters", '\Mu' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'P', '\Pi', "g:atp_imap_define_greek_letters", '\Pi' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'O', '\Theta', "g:atp_imap_define_greek_letters", '\Theta' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'S', '\Sigma', "g:atp_imap_define_greek_letters", '\Sigma' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'T', '\Tau', "g:atp_imap_define_greek_letters", '\Tau' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'U', '\Upsilon', "g:atp_imap_define_greek_letters", '\Upsilon' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'W', '\Omega', "g:atp_imap_define_greek_letters", '\Omega' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'Z', '\mathrm', "g:atp_imap_define_greek_letters", '\mathrm' ], \ ] endif " call atplib#MakeMaps(g:atp_imap_greek_letters) augroup ATP_MathIMaps_GreekLetters au! au CursorMovedI *.tex :call atplib#ToggleMathIMaps(g:atp_imap_greek_letters, 'CursorMovedI') au CursorHoldI *.tex :call atplib#ToggleMathIMaps(g:atp_imap_greek_letters, 'CursorHoldI') au InsertEnter *.tex :call atplib#ToggleMathIMaps(g:atp_imap_greek_letters, 'InsertEnter') " Make imaps visible with :imap /this will not work with i_CTRL-C/ au InsertLeave *.tex :call atplib#MakeMaps(g:atp_imap_greek_letters, 'InsertLeave') au BufEnter *.tex :call atplib#MakeMaps(g:atp_imap_greek_letters, 'BufEnter') augroup END if !exists("g:atp_imap_math_misc") || g:atp_reload_variables let leader = (g:atp_imap_first_leader == '#' ? '`' : g:atp_imap_first_leader ) let g:atp_imap_math_misc = [ \ [ 'inoremap', ' ', leader, '8', '\infty', "g:atp_imap_define_math_misc", '\infty' ], \ [ 'inoremap', ' ', leader, '6', '\partial', "g:atp_imap_define_math_misc", '\partial' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, '&', '\wedge', "g:atp_imap_define_math_misc", '\wedge' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 've', '\vee', "g:atp_imap_define_math_misc", '\vee' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'V', '\Vee', "g:atp_imap_define_math_misc", '\Vee' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, '+', '\bigcup', "g:atp_imap_define_math_misc", '\bigcup' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, '*', '\bigcap', "g:atp_imap_define_math_misc", '\bigcap' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, '\', '\backslash', "g:atp_imap_define_math_misc", '\backslash' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, 'N', '\Nabla', "g:atp_imap_define_math_misc", '\Nabla' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, '@', '\circ', "g:atp_imap_define_math_misc", '\circ' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, '=', '\equiv', "g:atp_imap_define_math_misc", '\equiv' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, '>', '\geq', "g:atp_imap_define_math_misc", '\geq' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, '<', '\leq', "g:atp_imap_define_math_misc", '\leq' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, '.', '\dot', "g:atp_imap_define_math_misc", '\dot' ], \ [ 'inoremap', ' ', g:atp_imap_first_leader, '/', '\frac{}{}F}i', "g:atp_imap_define_math_misc", '\frac{}{}' ], \ [ 'inoremap', ' ', g:atp_imap_over_leader, '`', '\grave{}', "g:atp_imap_define_math_misc", '\grave{}' ], \ [ 'inoremap', ' ', g:atp_imap_over_leader, 'v', '\check{}', "g:atp_imap_define_math_misc", '\check{}' ], \ [ 'inoremap', ' ', g:atp_imap_over_leader, '''', '\acute{}', "g:atp_imap_define_math_misc", '\acute{}' ], \ [ 'inoremap', ' ', g:atp_imap_over_leader, '.', '\dot{}', "g:atp_imap_define_math_misc", '\dot{}' ], \ [ 'inoremap', ' ', g:atp_imap_over_leader, '>', '\vec{}', "g:atp_imap_define_math_misc", '\vec{}' ], \ [ 'inoremap', ' ', g:atp_imap_over_leader, '_', '\bar{}', "g:atp_imap_define_math_misc", '\bar{}' ], \ [ 'inoremap', ' ', g:atp_imap_over_leader, '~', '\=(g:atp_imap_wide ? "wide" : "")tilde{}', "g:atp_imap_define_math_misc", '''\''.(g:atp_imap_wide ? "wide" : "")."tilde"' ], \ [ 'inoremap', ' ', g:atp_imap_over_leader, '^', '\=(g:atp_imap_wide ? "wide" : "" )hat{}', "g:atp_imap_define_math_misc", '''\''.(g:atp_imap_wide ? "wide" : "")."hat"' ], \ ] " \ [ 'inoremap', ' ', g:atp_imap_first_leader, '~', '\=(g:atp_imap_wide ? "wide" : "")tilde{}', "g:atp_imap_define_math_misc", '''\''.(g:atp_imap_wide ? "wide" : "")."tilde"' ], " \ [ 'inoremap', ' ', g:atp_imap_first_leader, '^', '\=(g:atp_imap_wide ? "wide" : "" )hat{}', "g:atp_imap_define_math_misc", '''\''.(g:atp_imap_wide ? "wide" : "")."hat"' ], endif " call atplib#MakeMaps(g:atp_imap_math_misc) augroup ATP_MathIMaps_misc au! au CursorMovedI *.tex :call atplib#ToggleMathIMaps(g:atp_imap_math_misc, 'CursorMovedI') au CursorHoldI *.tex :call atplib#ToggleMathIMaps(g:atp_imap_math_misc, 'CursorHoldI') au InsertEnter *.tex :call atplib#ToggleMathIMaps(g:atp_imap_math_misc, 'InsertEnter') " Make imaps visible with :imap /this will not work with i_CTRL-C/ au InsertLeave *.tex :call atplib#MakeMaps(g:atp_imap_math_misc, 'InsertLeave') au BufEnter *.tex :call atplib#MakeMaps(g:atp_imap_math_misc, 'BufEnter') augroup END if g:atp_no_env_maps != 1 " Left for backward compatibility " New mapping for the insert mode. if !exists("g:atp_imap_environments") || g:atp_reload_variables let g:atp_imap_environments = [ \ [ "inoremap", " ", g:atp_imap_third_leader, "m", '\(\)', "g:atp_imap_define_environments", 'inlince math' ], \ [ "inoremap", " ", g:atp_imap_third_leader, "M", '\[\]', "g:atp_imap_define_environments", 'displayed math' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_begin, '\begin{}', "g:atp_imap_define_environments", '\begin{}' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_end, '\end{}', "g:atp_imap_define_environments", '\end{}' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_proof, '\begin{proof}\end{proof}O', "g:atp_imap_define_environments", 'proof' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_center, '\begin{center}\end{center}O', "g:atp_imap_define_environments", 'center' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_flushleft, '\begin{flushleft}\end{flushleft}O', "g:atp_imap_define_environments", 'flushleft' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_flushright, '\begin{flushright}\end{flushright}O', "g:atp_imap_define_environments", 'flushright' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_bibliography, '\begin{thebibliography}\end{thebibliography}O', "g:atp_imap_define_environments", 'bibliography' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_abstract, '\begin{abstract}\end{abstract}O', "g:atp_imap_define_environments", 'abstract' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_item, ':call InsertItem()a', "g:atp_imap_define_environments", 'item' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_frame, '\begin{frame}\end{frame}O', "g:atp_imap_define_environments", 'frame' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_enumerate, '\begin{enumerate}'.g:atp_EnvOptions_enumerate.'\end{enumerate}O\item', "g:atp_imap_define_environments", 'enumerate' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_itemize, '\begin{itemize}'.g:atp_EnvOptions_itemize.'\end{itemize}O\item', "g:atp_imap_define_environments", 'itemize' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_tikzpicture, '\begin{center}\begin{tikzpicture}\end{tikzpicture}\end{center}O', "g:atp_imap_define_environments", 'tikzpicture' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_theorem, '\begin{=g:atp_EnvNameTheorem=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}\end{=g:atp_EnvNameTheorem=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}O', "g:atp_imap_define_environments", 'theorem'], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_definition, '\begin{=g:atp_EnvNameDefinition=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}\end{=g:atp_EnvNameDefinition=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}O', "g:atp_imap_define_environments", 'definition'], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_proposition, '\begin{=g:atp_EnvNameProposition=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}\end{=g:atp_EnvNameProposition=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}O', "g:atp_imap_define_environments", 'proposition' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_lemma, '\begin{=g:atp_EnvNameLemma=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}\end{=g:atp_EnvNameLemma=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}O', "g:atp_imap_define_environments", 'lemma' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_remark, '\begin{=g:atp_EnvNameRemark=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}\end{=g:atp_EnvNameRemark=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}O', "g:atp_imap_define_environments", 'remark' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_note, '\begin{=g:atp_EnvNameNote=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}\end{=g:atp_EnvNameNote=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}O', "g:atp_imap_define_environments", 'note' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_example, '\begin{example=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}\end{example=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}O', "g:atp_imap_define_environments", 'example' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_corollary, '\begin{=g:atp_EnvNameCorollary=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}\end{=g:atp_EnvNameCorollary=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}O', "g:atp_imap_define_environments", 'corollary' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_align, '\begin{align=(getline(".")[col(".")-2]=="*"?"":b:atp_StarMathEnvDefault)}\end{align=(getline(".")[col(".")-2]=="*"?"":b:atp_StarMathEnvDefault)}O', "g:atp_imap_define_environments", 'align' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_equation, '\begin{equation=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}\end{equation=(getline(".")[col(".")-2]=="*"?"":b:atp_StarEnvDefault)}O', "g:atp_imap_define_environments", 'equation' ], \ [ 'inoremap', ' ', g:atp_imap_third_leader, g:atp_imap_letter, '\begin{letter}{}\opening{=g:atp_letter_opening}\closing{=g:atp_letter_closing}\end{letter}?\\begin{letter}{\zsi', "g:atp_imap_define_environments", 'letter' ], \ ] endif call atplib#MakeMaps(g:atp_imap_environments) endif if !exists("g:atp_imap_math") || g:atp_reload_variables let g:atp_imap_math= [ \ [ "inoremap", " ", "", g:atp_imap_subscript, "!atplib#IsLeft('\\', 1) && atplib#IsInMath() ? '_{}' : '_' ", "g:atp_imap_define_math", '_{}'], \ [ "inoremap", " ", "", g:atp_imap_supscript, "!atplib#IsLeft('\\', 1) && atplib#IsLeft('^') && atplib#IsInMath() ? '^{}' : (atplib#IsLeft('~') ? '\\=(g:atp_imap_wide ? ''wide'' : '''' )hat{}' : '^') ", "g:atp_imap_define_math", '^{}'], \ [ "inoremap", " ", "", "~", "atplib#IsLeft('~') && atplib#IsInMath() ? '\\=(g:atp_imap_wide ? \"wide\" : \"\" ) tilde{}' : '~' " , "g:atp_imap_define_math", '^{}'], \ [ "inoremap", " ", "", "=", "atplib#IsInMath() && atplib#IsLeft('=') && !atplib#IsLeft('&',1) ? '&=' : '='", "g:atp_imap_define_math", '&=' ], \ [ "inoremap", " ", "", "o+", "atplib#IsInMath() ? '\\oplus' : 'o+' ", "g:atp_imap_define_math", '\\oplus' ], \ [ "inoremap", " ", "", "O+", "atplib#IsInMath() ? '\\bigoplus' : 'O+' ", "g:atp_imap_define_math", '\\bigoplus'], \ [ "inoremap", " ", "", "o-", "atplib#IsInMath() ? '\\ominus' : 'o-' ", "g:atp_imap_define_math", '\\ominus'], \ [ "inoremap", " ", "", "o.", "atplib#IsInMath() ? '\\odot' : 'o.' ", "g:atp_imap_define_math", '\\odot'], \ [ "inoremap", " ", "", "O.", "atplib#IsInMath() ? '\\bigodot' : 'O.' ", "g:atp_imap_define_math", '\\bigodot'], \ [ "inoremap", " ", "", "o*", "atplib#IsInMath() ? '\\otimes' : 'o*' ", "g:atp_imap_define_math", '\\otimes'], \ [ "inoremap", " ", "", "O*", "atplib#IsInMath() ? '\\bigotimes' : 'O*' ", "g:atp_imap_define_math", '\\bigotimes'], \ [ "inoremap", " ", "", "s+", "atplib#IsInMath() ? '\\cup' : 's+' ", "g:atp_imap_define_math", '\\cup'], \ [ "inoremap", " ", "", "s-", "atplib#IsInMath() ? '\\setminus' : 's-' ", "g:atp_imap_define_math", '\\cup'], \ [ "inoremap", " ", "", "S+", "atplib#IsInMath() ? '\\bigcup' : 'S+' ", "g:atp_imap_define_math", '\\bigcup'], \ [ "inoremap", " ", "", "s*", "atplib#IsInMath() ? '\\cap' : 's*' ", "g:atp_imap_define_math", '\\cap'], \ [ "inoremap", " ", "", "S*", "atplib#IsInMath() ? '\\bigcap' : 'S*' ", "g:atp_imap_define_math", '\\bigcap'], \ [ "inoremap", " ", "", "c*", "atplib#IsInMath() ? '\\prod' : 'c*' ", "g:atp_imap_define_math", '\\prod'], \ [ "inoremap", " ", "", "c+", "atplib#IsInMath() ? '\\coprod' : 'c+' ", "g:atp_imap_define_math", '\\coprod'], \ [ "inoremap", " ", "", "t<", "atplib#IsInMath() ? '\\triangleleft' : 't<' ", "g:atp_imap_define_math", '\\triangleleft'], \ [ "inoremap", " ", "", "t>", "atplib#IsInMath() ? '\\triangleright' : 't>' ", "g:atp_imap_define_math", '\\triangleright'], \ [ "inoremap", " ", "", "s<", "atplib#IsInMath() ? '\\subseteq' : 's<' ", "g:atp_imap_define_math", '\\subseteq'], \ [ "inoremap", " ", "", "s>", "atplib#IsInMath() ? '\\supseteq' : 's>' ", "g:atp_imap_define_math", '\\supseteq'], \ [ "inoremap", " ", "", "<=", "atplib#IsInMath() ? '\\leq' : '<=' ", "g:atp_imap_define_math", '\\leq'], \ [ "inoremap", " ", "", ">=", "atplib#IsInMath() ? '\\geq' : '>=' ", "g:atp_imap_define_math", '\\geq'], \ ] endif augroup ATP_MathIMaps au! au CursorMovedI *.tex :call atplib#ToggleMathIMaps(g:atp_imap_math, 'CursorMovedI') au CursorHoldI *.tex :call atplib#ToggleMathIMaps(g:atp_imap_math, 'CursorHoldI') au InsertEnter *.tex :call atplib#ToggleMathIMaps(g:atp_imap_math, 'InsertEnter') " Make imaps visible with :imap /this will not work with i_CTRL-C/ au InsertLeave *.tex :call atplib#MakeMaps(g:atp_imap_math, 'InsertLeave') au BufEnter *.tex :call atplib#MakeMaps(g:atp_imap_math, 'BufEnter') augroup END endif " vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1 ftplugin/ATP_files/abbreviations.vim [[[1 175 " 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 -+ \mp 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 260 " 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.&GotoLabel:GotoLabel :GotoLabel cmenu 550.40 LaTe&X.&Go\ to.&GotoLabel:GotoLabel GotoLabel imenu 550.40 LaTe&X.&Go\ to.&GotoLabel:GotoLabel :GotoLabel menu 550.40 LaTe&X.&Go\ to.&GotoNamedDest(Xpdf\ only) :GotoNamedDest cmenu 550.40 LaTe&X.&Go\ to.&GotoNamedDest(Xpdf\ only) GotoNamedDest imenu 550.40 LaTe&X.&Go\ to.&GotoNamedDest(Xpdf\ only) :GotoNamedDest " 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_OutDir=" cmenu 550.70 LaTe&X.&Options.Set\ Output\ Directoryb:atp_OutDir let b:atp_OutDir=" imenu 550.70 LaTe&X.&Options.Set\ Output\ Directoryb:atp_OutDir :let b:atp_OutDir=" menu 550.70 LaTe&X.&Options.Set\ Viewer\ Options :let b:atp_{matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')}Options= cmenu 550.70 LaTe&X.&Options.Set\ Viewer\ Options let b:atp_{matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')}Options= imenu 550.70 LaTe&X.&Options.Set\ Viewer\ Options :let b:atp_{matchstr(b:atp_Viewer, '^\s*\zs\S\+\ze')}Options= 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.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 1804 " 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 "{{{1 " All table of contents stuff: variables, functions and commands. " {{{2 Table Of Contents "--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 / " " {{{3 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 " {{{3 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 return { a:filename : toc } endfunction " {{{3 s:buflist if !exists("t:atp_toc_buflist") let t:atp_toc_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: if !exists("t:atp_toc_buflist") let t:atp_toc_buflist = [] endif let name=resolve(fnamemodify(bufname("%"),":p")) " add an entry to the list t:atp_toc_buflist if it is not there. if bufname("") =~ ".tex" && index(t:atp_toc_buflist,name) == -1 call add(t:atp_toc_buflist,name) endif return t:atp_toc_buflist endfunction " {{{3 RemoveFromBufList function! RemoveFromToC(file) if a:file == "" let g:debug = 1 if exists("b:atp_MainFile") let list = filter(copy(t:atp_toc_buflist), "v:val != fnamemodify(b:atp_MainFile, ':p')") else let list = copy(t:atp_toc_buflist) endif if len(list) >= 2 let i=1 for f in list echo "(" . i . ") " . f let i+=1 endfor let which=input("Which file to remove (press for none)") if which == "" let g:debug=3 return endif let which=t:atp_toc_buflist[which-1] elseif exists("b:atp_MainFile") && len(list) == 1 let which=get(list,0,"") else return endif else let which = fnamemodify(a:file, ":p") endif let g:which = which if which != "" silent! call remove(t:atp_toc_buflist,index(t:atp_toc_buflist, which)) silent! call remove(t:atp_toc,which) endif let winnr=winnr() call TOC("!", 0) exe winnr."wincmd w" endfunction function! RemoveFromToCComp(A, B, C) if exists("b:atp_MainFile") let list = filter(copy(t:atp_toc_buflist), "v:val != fnamemodify(b:atp_MainFile, ':p')") else let list = copy(t:atp_toc_buflist) endif return join(list,"\n") endfunction " {{{3 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 . "$") 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") let t:toc_window_width = g:atp_toc_window_width endif let openbuffer="keepalt " . t:toc_window_width . "vsplit +setl\\ wiw=15\\ buftype=nofile\\ nobuflisted\\ 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 = {} let s:numberdict = 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', \ ':YankSection', \ ':DeleteSection', \ ':PasteSection', \ ':SectionStack', \ ':Undo' ]) endif lockvar 3 b:atp_Toc endfunction " {{{3 ToCOpen() " This function returns toc buffer number if toc window is not open returns -1. function! ToCbufnr() return index(map(tabpagebuflist(), 'bufname(v:val)'), '__ToC__') endfunction " {{{3 UpdateToCLine function! UpdateToCLine(...) if !g:atp_UpdateToCLine return endif let toc_bufnr = ToCbufnr() let check_line = (a:0>=1 ? a:1 : -1) if toc_bufnr == -1 || check_line != -1 && \ getline(line(".")+check_line) !~# '\\\%(part\|chapter\|\%(sub\)\{0,2}section\)\s*{' return endif let cline = line(".") let cbufnr = bufnr("") let cwinnr = bufwinnr("") exe toc_bufnr."wincmd w" let num = get(s:numberdict, t:atp_bufname, 'no_number') if num == 'no_number' exe cwinnr."wincmd w" return endif let sorted = sort(keys(t:atp_toc[t:atp_bufname]), "atplib#CompareNumbers") for line in sorted if cline>=line let num+=1 endif keepjumps call setpos('.',[bufnr(""),num,1,0]) endfor exe cwinnr."wincmd w" endfunction " This is User Front End Function "{{{3 TOC function! TOC(bang,...) " skip generating t:atp_toc list if it exists and if a:0 != 0 if &l:filetype != 'tex' && &l:filetype != 'toc_atp' echoerr "Wrong 'filetype'. This command works only for latex documents." return endif if a:0 == 0 call s:buflist() endif " for each buffer in t:atp_toc_buflist (set by s:buflist) if ( a:bang == "!" || !exists("t:atp_toc") ) let t:atp_toc = {} for buffer in t:atp_toc_buflist " let t:atp_toc=s:maketoc(buffer) call extend(t:atp_toc, s:maketoc(buffer)) endfor endif call s:showtoc(t:atp_toc) endfunction nnoremap ATP_TOC :call TOC("") " This finds the name of currently eddited section/chapter units. " {{{3 Current TOC " ToDo: make this faster! " {{{3 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 " {{{3 s:ctoc function! 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) if !exists("t:atp_toc") let t:atp_toc={} endif silent call extend(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 " {{{3 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 g:names=names 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 "}}}3 " Labels Front End Finction. The search engine/show function are in autoload/atplib.vim script " library. " {{{2 Labels " a:bang = "!" do not regenerate labels if not necessary function! Labels(bang) let t:atp_bufname = bufname("%") let error = ( exists("b:atp_TexReturnCode") ? b:atp_TexReturnCode : 0 ) 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 "[ATP:] the compelation contains errors, aux file might be not appriopriate for labels window." echohl Normal endif endfunction nnoremap ATP_Labels :call Labels("") " GotoLabel & GotoLabelCompletion {{{2 " 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 || file == atplib#FullPath(b:atp_MainFile) 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 "[ATP:] 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]]") " else " Show File from which label comes " The reason to not use this is as follows: " it only matters for project files, which probably have many " labels, so it's better to make the list as concise as possible " 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 g:mlabels=copy(mlabels) for row in atplib#FormatListinColumns(atplib#Table(mlabels, [1,2]),2) echo join(row) endfor let nr = input("Which label to choose? type number and press ")-1 if nr < 0 || nr >= len(matches) return endif 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 || file == atplib#FullPath(b:atp_MainFile) 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 "{{{2 GotoDestination function! GotoNamedDestination(destination) if b:atp_Viewer !~ '^\s*xpdf\>' echomsg "[ATP:] this only works with Xpdf viewer." return 0 endif let cmd='xpdf -remote '.b:atp_XpdfServer.' -exec gotoDest\("'.a:destination.'"\)' " let g:cmd=cmd call system(cmd) endfunction function! FindDestinations() let files = [ b:atp_MainFile ] if !exists("b:TypeDict") call TreeOfFiles(b:atp_MainFile) endif for file in keys(b:TypeDict) if b:TypeDict[file] == 'input' call add(files, file) endif endfor let saved_loclist = getloclist(0) exe 'lvimgrep /\\hypertarget\>/gj ' . join(map(files, 'fnameescape(v:val)'), ' ') let dests = [] let loclist = copy(getloclist(0)) let g:loclist = loclist call setloclist(0, saved_loclist) for loc in loclist let destname = matchstr(loc['text'], '\\hypertarget\s*{\s*\zs[^}]*\ze}') call add(dests, destname) endfor return dests endfunction function! CompleteDestinations(ArgLead, CmdLine, CursorPos) let dests=FindDestinations() return join(dests, "\n") endfunction " Motion functions through environments and sections. " {{{2 Motion functions " Go to next environment "{{{3 " which name is given as the argument. Do not wrap " around the end of the file. function! GotoEnvironment(flag,count,...) " Options : let env_name = ( a:0 >= 1 && a:1 != "" ? a:1 : '[^}]*' ) if env_name == 'part' if a:flag =~ 'b' exe a:count.'PPart' return else exe a:count.'NPart' return endif elseif env_name == 'chapter' if a:flag =~ 'b' exe a:count.'PChap' return else exe a:count.'NChap' return endif elseif env_name == 'section' if a:flag =~ 'b' exe a:count.'PSec' return else exe a:count.'NSec' return endif elseif env_name == 'subsection' if a:flag =~ 'b' exe a:count.'PSSec' return else exe a:count.'NSSec' return endif elseif env_name == 'subsubsection' if a:flag =~ 'b' exe a:count.'PSSSec' return else exe a:count.'NSSSec' return endif endif let flag = a:flag " Set the search tool : " Set the pattern : if env_name == 'math' let pattern = '\m\%(\(\\\@ 1 " the 's' flag should be used only in the first search. let flag=substitute(flag, 's', '', 'g') endif if g:atp_mapNn let search_cmd = "S /" let search_cmd_e= "/ " . flag else let search_cmd = "silent! call search('" let search_cmd_e= "','" . flag . "')" endif execute search_cmd . pattern . search_cmd_e if a:flag !~# 'b' if getline(".")[col(".")-1] == "$" if ( get(split(getline("."), '\zs'), col(".")-1, '') == "$" && get(split(getline("."), '\zs'), col("."), '') == "$" ) "check $$ let rerun = !atplib#CheckSyntaxGroups(['texMathZoneY'], line("."), col(".")+1 ) elseif get(split(getline("."), '\zs'), col(".")-1, '') == "$" "check $ let rerun = !atplib#CheckSyntaxGroups(['texMathZoneX', 'texMathZoneY'], line("."), col(".") ) endif if rerun silent! execute search_cmd . pattern . search_cmd_e endif endif else " a:flag =~# 'b' if getline(".")[col(".")-1] == "$" if ( get(split(getline("."), '\zs'), col(".")-1, '') == "$" && get(split(getline("."), '\zs'), col(".")-2, '') == "$" ) "check $$ let rerun = atplib#CheckSyntaxGroups(['texMathZoneY'], line("."), col(".")-3 ) elseif get(split(getline("."), '\zs'), col(".")-1, '') == "$" "check $ let rerun = atplib#CheckSyntaxGroups(['texMathZoneX', 'texMathZoneY'], line("."), col(".")-2 ) endif if rerun silent! execute search_cmd . pattern . search_cmd_e endif endif endif endfor call UpdateToCLine() silent! call histadd("search", pattern) silent! let @/ = pattern return "" endfunction " function! GotoEnvironmentB(flag,count,...) " let env_name = (a:0 >= 1 && a:1 != "" ? a:1 : '[^}]*') " for i in range(1,a:count) " let flag = (i!=1?substitute(a:flag, 's', '', 'g'):a:flag) " call GotoEnvironment(flag,1,env_name) " endfor " endfunction " Jump over current \begin and go to next one. {{{3 " i.e. if on line =~ \begin => % and then search, else search function! JumptoEnvironment(backward) call setpos("''", getpos(".")) let lazyredraw=&l:lazyredraw set lazyredraw if !a:backward let col = searchpos('\w*\>\zs', 'n')[1]-1 if strpart(getline(line(".")), 0, col) =~ '\\begin\>$' && \ strpart(getline(line(".")), col) !~ '^\s*{\s*document\s*}' exe "normal %" endif call search('^\%([^%]\|\\%\)*\zs\\begin\>', 'W') else let found = search('^\%([^%]\|\\%\)*\\end\>', 'bcW') if getline(line(".")) !~ '^\%([^%]\|\\%\)*\\end\s*{\s*document\s*}' && found exe "normal %" elseif !found call search('^\%([^%]\|\\%\)*\zs\\begin\>', 'bW') endif endif let &l:lazyredraw=lazyredraw endfunction " Go to next section {{{3 " 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, count, 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) ? '^\([^%]\|\\\@ 1 " the 's' flag should be used only in the first search. let flag=substitute(flag, 's', '', 'g') endif if search_tool == 'vim' call searchpos(bpat . pattern, flag) else execute "S /". bpat . pattern . "/ " . flag endif endfor call UpdateToCLine() call histadd("search", pattern) let @/ = pattern " If ToC is shown jump to and come back let toc_winnr=bufwinnr(bufnr("__ToC__")) if toc_winnr != -1 let cwin=winnr() exe toc_winnr." wincmd w" redraw exe cwin." wincmd w" endif endfunction function! Env_compl(A,P,L) let envlist=sort(['algorithm', 'algorithmic', 'abstract', 'definition', 'equation', 'proposition', \ 'theorem', 'lemma', 'array', 'tikzpicture', \ 'tabular', 'table', 'align', 'alignat', 'proof', \ 'corollary', 'enumerate', 'examples\=', 'itemize', 'remark', \ 'notation', 'center', 'quotation', 'quote', 'tabbing', \ 'picture', 'math', 'displaymath', 'minipage', 'list', 'flushright', 'flushleft', \ 'frame', 'figure', 'eqnarray', 'thebibliography', 'titlepage', \ 'verbatim', 'verse', 'inlinemath', 'displayedmath', 'subequations', \ 'part', 'section', 'subsection', 'subsubsection' ]) let returnlist=[] for env in envlist if env =~ '^' . a:A call add(returnlist,env) endif endfor return returnlist endfunction function! ggGotoSection(count,section) let mark = getpos("''") if a:section == "part" let secname = '\\part\>' call cursor(1,1) elseif a:section == "chapter" let secname = '\\\%(part\|chapter\)\>' if !search('\\part\>', 'bc') call cursor(1,1) endif elseif a:section == "section" let secname = '\\\%(part\|chapter\|section\)\>' if !search('\\chapter\>\|\\part\>', 'bc') call cursor(1,1) endif elseif a:section == "subsection" let secname = '\\\%(part\|chapter\|section\|subsection\)\>' if !search('\\section\>\|\\chapter\>\|\\part\>', 'bc') call cursor(1,1) endif elseif a:section == "subsubsection" let secname = '\\\%(part\|chapter\|section\|subsection\|subsubsection\)\>' if !search('\subsection\>\|\\section\>\|\\chapter\>\|\\part\>', 'bc') call cursor(1,1) endif endif call UpdateToCLine() call GotoSection("", a:count, 'Ws', secname) call setpos("''",mark) endfunction " {{{3 Input() function function! 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") let atp_ErrorFormat = b:atp_ErrorFormat let atp_LastLatexPID = ( exists("b:atp_LastLatexPID") ? b:atp_LastLatexPID : 0 ) let atp_LatexPIDs = ( exists("b:atp_LatexPIDs") ? b:atp_LatexPIDs : [] ) let atp_BibtexPIDs = ( exists("b:atp_BibtexPIDs") ? b:atp_BibtexPIDs : [] ) let atp_MakeindexPIDs = ( exists("b:atp_MakeindexPIDs") ? b:atp_MakeindexPIDs : [] ) let atp_ProgressBar = ( exists("b:atp_ProgressBar") ? b:atp_ProgressBar : {} ) 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) if exists("b:atp_ErrorFormat") unlockvar b:atp_ErrorFormat endif let b:atp_ErrorFormat = atp_ErrorFormat let [ b:TreeOfFiles, b:ListOfFiles, b:TypeDict, b:LevelDict ] = deepcopy([tree_d, file_l_orig, type_d, level_d ]) if exists("b:atp_ProgressBar") unlockvar b:atp_ProgressBar endif let [ b:atp_LastLatexPID, b:atp_LatexPIDs, b:atp_ProgressBar ] = [ atp_LastLatexPID, atp_LatexPIDs, atp_ProgressBar ] let [ b:atp_BibtexPIDs, b:atp_MakeindexPIDs ] = [ atp_BibtexPIDs, atp_MakeindexPIDs ] lockvar b:atp_ProgressBar 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 "{{{2 " 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 " {{{2 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 " 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 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 " {{{2 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 " }}}1 " Commands And Maps: augroup ATP_BufList " Add opened files to t:atp_toc_buflist. au! au BufEnter *.tex call s:buflist() augroup END " {{{1 command! -nargs=? -complete=custom,RemoveFromToCComp RemoveFromToC :call RemoveFromToC() map JumptoPreviousEnvironment :call JumptoEnvironment(1) map JumptoNextEnvironment :call JumptoEnvironment(0) command! -buffer -count=1 Part :call ggGotoSection(, 'part') command! -buffer -count=1 Chap :call ggGotoSection(, 'chapter') command! -buffer -count=1 Sec :call ggGotoSection(, 'section') command! -buffer -count=1 SSec :call ggGotoSection(, 'subsection') command! -buffer -nargs=1 -complete=custom,CompleteDestinations GotoNamedDest :call GotoNamedDestination() 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,EnvCompletionWithoutStarEnvs Nenv :call GotoEnvironment('sW',,) | let v:searchforward=1 command! -buffer -count=1 -nargs=? -complete=customlist,EnvCompletionWithoutStarEnvs Penv :call GotoEnvironment('bsW',,) | let v:searchforward=0 "TODO: These two commands should also work with sections. command! -buffer -count=1 -nargs=? -complete=custom,F_compl F :call GotoEnvironment('sW',,) | let v:searchforward=1 command! -buffer -count=1 -nargs=? -complete=custom,F_compl B :call GotoEnvironment('bsW',,) | let v:searchforward=0 nnoremap GotoNextEnvironment :call GotoEnvironment('sW',v:count1,'') nnoremap GotoPreviousEnvironment :call GotoEnvironment('bsW',v:count1,'') nnoremap GotoNextMath :call GotoEnvironment('sW',v:count1,'math') nnoremap GotoPreviousMath :call GotoEnvironment('bsW',v:count1,'math') nnoremap GotoNextInlineMath :call GotoEnvironment('sW',v:count1,'inlinemath') nnoremap GotoPreviousInlineMath :call GotoEnvironment('bsW',v:count1,'inlinemath') nnoremap GotoNextDisplayedMath :call GotoEnvironment('sW',v:count1,'displayedmath') nnoremap GotoPreviousDisplayedMath :call GotoEnvironment('bsW',v:count1,'displayedmath') nnoremap GotoNextSubSection :call GotoSection("", v:count1, "s", "\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\*\\=\\>", ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', '') onoremap GotoNextSubSection :call GotoSection("", v:count1, "s","\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\*\\=\\>", 'vim') vnoremap vGotoNextSubSection m':exe "normal! gv"exe "normal! w"call search('^\([^%]\\|\\\@\\|\\end\s*{\s*document\s*}', 'W')exe "normal! b" nnoremap GotoNextSection :call GotoSection("", v:count1, "s", "\\\\\\%(section\\\\|chapter\\\\|part\\)\\*\\=\\>", ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', '') onoremap GotoNextSection :call GotoSection("", v:count1, "s", "\\\\\\%(section\\\\|chapter\\\\|part\\)\\*\\=\\>", 'vim') vnoremap vGotoNextSection m':exe "normal! gv"exe "normal! w"call search('^\([^%]\\|\\\@\\|\\end\s*{\s*document\s*}', 'W')exe "normal! b" nnoremap GotoNextChapter :call GotoSection("", v:count1, "s", "\\\\\\%(chapter\\\\|part\\)\\*\\=\\>", ( g:atp_mapNn ? 'atp' : 'vim' )) onoremap GotoNextChapter :call GotoSection("", v:count1, "s", "\\\\\\%(chapter\\\\|part\\)\\*\\=\\>", 'vim') vnoremap vGotoNextChapter m':exe "normal! gv"exe "normal! w"call search('^\([^%]\\|\\\@\\|\\end\s*{\s*document\s*}', 'W')exe "normal! b" nnoremap GotoNextPart :call GotoSection("", v:count1, "s", "\\\\part\\*\\=\\>", ( g:atp_mapNn ? 'atp' : 'vim' ), 'n') onoremap GotoNextPart :call GotoSection("", v:count1, "s", "\\\\part\\*\\=\\>", 'vim', 'n') vnoremap vGotoNextPart m':exe "normal! gv"exe "normal! w"call search('^\([^%]\\|\\\@\\|\\end\s*{\s*document\s*}\)', 'W')exe "normal! b" command! -buffer -bang -count=1 -nargs=? -complete=customlist,Env_compl NSSSec :call GotoSection(, , "s", '\\\%(subsubsection\|subsection\|section\|chapter\|part\)\*\=\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', ) command! -buffer -bang -count=1 -nargs=? -complete=customlist,Env_compl NSSec :call GotoSection(, , "s", '\\\%(subsection\|section\|chapter\|part\)\*\=\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', ) command! -buffer -bang -count=1 -nargs=? -complete=customlist,Env_compl NSec :call GotoSection(, , "s", '\\\%(section\|chapter\|part\)\*\=\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', ) command! -buffer -bang -count=1 -nargs=? -complete=customlist,Env_compl NChap :call GotoSection(, , "s", '\\\%(chapter\|part\)\*\=\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', ) command! -buffer -bang -count=1 -nargs=? -complete=customlist,Env_compl NPart :call GotoSection(, , "s", '\\part\*\=\>', ( g:atp_mapNn ? 'atp' : 'vim' ), 'n', ) nnoremap GotoPreviousSubSection :call GotoSection("", v:count1, "sb", "\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\*\\>", ( g:atp_mapNn ? 'atp' : 'vim' ), 'n') onoremap GotoPreviousSubSection :call GotoSection("", v:count1, "sb", "\\\\\\%(subsection\\\\|section\\\\|chapter\\\\|part\\)\\*\\>", 'vim') vnoremap vGotoPreviousSubSection m':exe "normal! gv"call search('\\\%(subsection\\|section\\|chapter\\|part\)\*\=\>\\|\\begin\s*{\s*document\s*}', 'bW') nnoremap GotoPreviousSection :call GotoSection("", v:count1, "sb", "\\\\\\%(section\\\\|chapter\\\\|part\\)\\*\\>", ( g:atp_mapNn ? 'atp' : 'vim' ), 'n') onoremap GotoPreviousSection :call GotoSection("", v:count1, "sb", "\\\\\\%(section\\\\|chapter\\\\|part\\)\\*\\>", 'vim') vnoremap vGotoPreviousSection m':exe "normal! gv"call search('\\\%(section\\|chapter\\|part\)\*\=\>\\|\\begin\s*{\s*document\s*}', 'bW') nnoremap GotoPreviousChapter :call GotoSection("", v:count1, "sb", "\\\\\\%(chapter\\\\|part\\)\\>", ( g:atp_mapNn ? 'atp' : 'vim' )) onoremap GotoPreviousChapter :call GotoSection("", v:count1, "sb", "\\\\\\%(chapter\\\\|part\\)\\>", 'vim') vGotoPreviousChapter m':exe "normal! gv"call search('\\\%(chapter\\|part\)\*\=\>\\|\\begin\s*{\s*document\s*}', 'bW') nnoremap GotoPreviousPart :call GotoSection("", v:count1, "sb", "\\\\part\\*\\=\\>", ( g:atp_mapNn ? 'atp' : 'vim' )) onoremap GotoPreviousPart :call GotoSection("", v:count1, "sb", "\\\\part\\*\\=\\>", 'vim') vnoremap vGotoPreviousPart m':exe "normal! gv"call search('\\\%(part\*\=\)\>', 'bW') command! -buffer -bang -count=1 -nargs=? -complete=customlist,Env_compl PSSSec :call GotoSection(, , 'sb', '\\\%(\%(sub\)\{1,2}section\|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\*\=\>', ( 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 command! -bang -nargs=? -complete=customlist,GotoLabelCompletion GotoLabel :call GotoLabel(, ) ftplugin/ATP_files/options.vim [[[1 2778 " 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 "{{{ 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_debugSyncTex") " debug SyncTex (compiler.vim) let g:atp_debugSyncTex = 0 endif if !exists("g:atp_debugInsertItem") " debug SyncTex (various.vim) let g:atp_debugInsertItem = 0 endif if !exists("g:atp_debugUpdateATP") " debug UpdateATP (various.vim) let g:atp_debugUpdateATP = 0 endif if !exists("g:atp_debugPythonCompiler") " debug MakeLatex (compiler.vim) let g:atp_debugPythonCompiler = 0 endif 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_debugRS") " debug RecursiveSearch (search.vim) let g:atp_debugRS = 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_debugCallBack") " 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_debugCloseLastEnvironment") " Debug atplib#CloseLastEnvironment() let g:atp_debugCloseLastEnvironment = 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_debugChekBracket") " atplib#CheckBracket() let g:atp_debugCheckBracket = 0 endif if !exists("g:atp_debugClostLastBracket") " atplib#CloseLastBracket() let g:atp_debugCloseLastBracket = 0 endif if !exists("g:atp_debugTabCompletion") " 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 if maparg("K", "n") != "" try nunmap K catch E31: nunmap K endtry endif exe "setlocal complete+=". \ "k".globpath(&rtp, "ftplugin/ATP_files/dictionaries/greek"). \ ",k".globpath(&rtp, "ftplugin/ATP_files/dictionaries/dictionary"). \ ",k".globpath(&rtp, "ftplugin/ATP_files/dictionaries/SIunits") " The ams_dictionary is added after g:atp_amsmath variable is defined. setlocal suffixes+=pdf " As a base we use the standard value defined in " The suffixes option is also set after g:atp_tex_extensions is set. " 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_autex_wait" : 0, \ "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_okularOptions" : ["--unique"], \ "atp_OutDir" : substitute(fnameescape(fnamemodify(resolve(expand("%:p")),":h")) . "/", '\\\s', ' ' , 'g'), \ "atp_TempDir" : substitute(b:atp_OutDir . "/.tmp", '\/\/', '\/', 'g'), \ "atp_TexCompiler" : &filetype == "plaintex" ? "pdftex" : "pdflatex", \ "atp_BibCompiler" : ( getline(atplib#SearchPackage('biblatex')) =~ '\' ? 'biber' : "bibtex" ), \ "atp_auruns" : "1", \ "atp_TruncateStatusSection" : "40", \ "atp_LastBibPattern" : "", \ "atp_TexCompilerVariable" : "max_print_line=2000", \ "atp_StarEnvDefault" : "", \ "atp_StarMathEnvDefault" : "", \ "atp_LatexPIDs" : [], \ "atp_BibtexPIDs" : [], \ "atp_PythonPIDs" : [], \ "atp_MakeindexPIDs" : [], \ "atp_LastLatexPID" : 0, \ "atp_LastPythonPID" : 0, \ "atp_VerboseLatexInteractionMode" : "errorstopmode", \ "atp_BibtexReturnCode" : 0, \ "atp_ProgressBar" : {}, \ "atp_BibtexOutput" : ""} " \ "atp_BibCompiler" : ( getline(atplib#SearchPackage('biblatex')) =~ '\' ? 'biber' : "bibtex" ), " \ "atp_TexCompilerVariable" : "", " \.";TEXINPUT=" " \.($TEXINPUTS == "" ? b:atp_OutDir : b:atp_OutDir.":".$TEXINPUTS) " \.";BIBINPUTS=" " \.($BIBINPUTS == "" ? b:atp_OutDir : b:atp_OutDir.":".$BIBINPUTS), 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 g:optionsKeys = copy(s:optionsKeys) 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 "[ATP:] b:atp_MainFile: ".b:atp_MainFile." doesn't exists." endif endif endfunction "}}} call s:SetOptions() lockvar b:atp_autex_wait "}}} " Global Variables: (almost all) " {{{ global variables if !exists("g:atp_sections") " Used by :TOC command (s:maketoc in motion.vim) let g:atp_sections={ \ 'chapter' : [ '\m^\s*\(\\chapter\*\?\>\)', '\m\\chapter\*'], \ 'section' : [ '\m^\s*\(\\section\*\?\>\)', '\m\\section\*'], \ 'subsection' : [ '\m^\s*\(\\subsection\*\?\>\)', '\m\\subsection\*'], \ 'subsubsection' : [ '\m^\s*\(\\subsubsection\*\?\>\)', '\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\*\?\>\)', '\m\\part\*']} endif if !exists("g:atp_cgetfile") || g:atp_reload_variables let g:atp_cgetfile = 1 endif if !exists("g:atp_atpdev") || g:atp_reload_variables " if 1 defines DebugPrint command to print log files from g:atp_Temp directory. let g:atp_atpdev = 0 endif if !exists("g:atp_imap_ShortEnvIMaps") || g:atp_reload_variables " By default 1, then one letter (+leader) mappings for environments are defined, " for example ]t -> \begin{theorem}\end{theorem} " if 0 three letter maps are defined: ]the -> \begin{theorem}\end{theorem} let g:atp_imap_ShortEnvIMaps = 1 endif if !exists("g:atp_imap_over_leader") || g:atp_reload_variables let g:atp_imap_over_leader="`" endif if !exists("g:atp_imap_subscript") || g:atp_reload_variables let g:atp_imap_subscript="__" endif if !exists("g:atp_imap_supscript") || g:atp_reload_variables let g:atp_imap_supscript="^" endif if !exists("g:atp_imap_define_math") || g:atp_reload_variables let g:atp_imap_define_math=1 endif if !exists("g:atp_imap_define_environments") || g:atp_reload_variables let g:atp_imap_define_environments = 1 endif if !exists("g:atp_imap_define_math_misc") || g:atp_reload_variables let g:atp_imap_define_math_misc = 1 endif if !exists("g:atp_imap_define_greek_letters") || g:atp_reload_variables let g:atp_imap_define_greek_letters = 1 endif if !exists("g:atp_imap_wide") || g:atp_reload_variables let g:atp_imap_wide=0 endif if !exists("g:atp_letter_opening") || g:atp_reload_variables let g:atp_letter_opening="" endif if !exists("g:atp_letter_closing") || g:atp_reload_variables let g:atp_letter_closing="" endif if !exists("g:atp_imap_bibiliography") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_letter="" else let g:atp_imap_letter="let" endif endif if !exists("g:atp_imap_bibiliography") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_bibliography="B" else let g:atp_imap_bibliography="bib" endif endif if !exists("g:atp_imap_begin") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_begin="b" else let g:atp_imap_begin="beg" endif endif if !exists("g:atp_imap_end") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_end="e" else let g:atp_imap_end="end" endif endif if !exists("g:atp_imap_theorem") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_theorem="t" else let g:atp_imap_theorem="the" endif endif if !exists("g:atp_imap_definition") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_definition="d" else let g:atp_imap_definition="def" endif endif if !exists("g:atp_imap_proposition") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_proposition="P" else let g:atp_imap_proposition="Pro" endif endif if !exists("g:atp_imap_lemma") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_lemma="l" else let g:atp_imap_lemma="lem" endif endif if !exists("g:atp_imap_remark") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_remark="r" else let g:atp_imap_remark="rem" endif endif if !exists("g:atp_imap_corollary") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_corollary="c" else let g:atp_imap_corollary="cor" endif endif if !exists("g:atp_imap_proof") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_proof="p" else let g:atp_imap_proof="pro" endif endif if !exists("g:atp_imap_example") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_example="x" else let g:atp_imap_example="exa" endif endif if !exists("g:atp_imap_note") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_note="n" else let g:atp_imap_note="not" endif endif if !exists("g:atp_imap_enumerate") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_enumerate="E" else let g:atp_imap_enumerate="enu" endif endif if !exists("g:atp_imap_itemize") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_itemize="I" else let g:atp_imap_itemize="ite" endif endif if !exists("g:atp_imap_item") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_item="i" else let g:atp_imap_item="I" endif endif if !exists("g:atp_imap_align") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_align="a" else let g:atp_imap_align="ali" endif endif if !exists("g:atp_imap_abstract") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_abstract="A" else let g:atp_imap_abstract="abs" endif endif if !exists("g:atp_imap_equation") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_equation="q" else let g:atp_imap_equation="equ" endif endif if !exists("g:atp_imap_center") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_center="C" else let g:atp_imap_center="cen" endif endif if !exists("g:atp_imap_flushleft") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_flushleft="L" else let g:atp_imap_flushleft="lef" endif endif if !exists("g:atp_imap_flushright") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_flushright="R" else let g:atp_imap_flushright="rig" endif endif if !exists("g:atp_imap_tikzpicture") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_tikzpicture="T" else let g:atp_imap_tikzpicture="tik" endif endif if !exists("g:atp_imap_frame") || g:atp_reload_variables if g:atp_imap_ShortEnvIMaps let g:atp_imap_frame="f" else let g:atp_imap_frame="fra" endif endif if !exists("g:atp_goto_section_leader") || g:atp_reload_variables let g:atp_goto_section_leader="-" endif if !exists("g:atp_autex_wait") " the value is a comma speareted list of modes, for modes see mode() function. " let g:atp_autex_wait = "i,R,Rv,no,v,V,c,cv,ce,r,rm,!" let g:atp_autex_wait = "" endif if !exists("g:atp_MapSelectComment") || g:atp_reload_variables let g:atp_MapSelectComment = "_c" endif if exists("g:atp_latexpackages") || g:atp_reload_variables " Transition to nicer name: let g:atp_LatexPackages = g:atp_latexpackages unlet g:atp_latexpackages endif if exists("g:atp_latexclasses") || g:atp_reload_variables " Transition to nicer name: let g:atp_LatexClasses = g:atp_latexclasses unlet g:atp_latexclasses endif if !exists("g:atp_Python") || g:atp_reload_variables " This might be a name of python executable or full path to it (if it is not in " the $PATH) if has("win32") || has("win64") " TO BE TESTED: " see why to use "pythonw.exe" on: " "http://docs.python.org/using/windows.html". let g:atp_Python = "pythonw.exe" else let g:atp_Python = "python" endif endif if !exists("g:atp_UpdateToCLine") || g:atp_reload_variables let g:atp_UpdateToCLine = 1 endif if !exists("g:atp_DeleteWithBang") || g:atp_reload_variables let g:atp_DeleteWithBang = [ 'synctex.gz', 'tex.project.vim'] endif if !exists("g:atp_CommentLeader") || g:atp_reload_variables let g:atp_CommentLeader="% " endif if !exists("g:atp_MapCommentLines") || g:atp_reload_variables let g:atp_MapCommentLines = 1 endif if !exists("g:atp_XpdfSleepTime") || g:atp_reload_variables let g:atp_XpdfSleepTime = "0.2" endif if !exists("g:atp_MapCC") || g:atp_reload_variables let g:atp_MapCC = 0 endif if !exists("g:atp_DefaultErrorFormat") || g:atp_reload_variables let g:atp_DefaultErrorFormat = "erc" endif let b:atp_ErrorFormat = g:atp_DefaultErrorFormat if !exists("g:atp_DefiSearchMaxWindowHeight") || g:atp_reload_variables let g:atp_DefiSearchMaxWindowHeight=15 endif if !exists("g:atp_ProgressBar") || g:atp_reload_variables let g:atp_ProgressBar = 1 endif let g:atp_cmdheight = &l:cmdheight if !exists("g:atp_DebugModeQuickFixHeight") || g:atp_reload_variables let g:atp_DebugModeQuickFixHeight = 8 endif if !exists("g:atp_DebugModeCmdHeight") || g:atp_reload_variables let g:atp_DebugModeCmdHeight = &l:cmdheight endif if !exists("g:atp_DebugMode_AU_change_cmdheight") || g:atp_reload_variables " Background Compilation will change the 'cmdheight' option when the compilation " was without errors. AU - autocommand compilation let g:atp_DebugMode_AU_change_cmdheight = 0 " This is the 'stay out of my way' solution. endif if !exists("g:atp_Compiler") || g:atp_reload_variables let g:atp_Compiler = "python" endif if !exists("g:atp_ReloadViewers") || g:atp_reload_variables " List of viewers which need to be reloaded after output file is updated. let g:atp_ReloadViewers = [ 'xpdf' ] endif if !exists("g:atp_PythonCompilerPath") || g:atp_reload_variables let g:atp_PythonCompilerPath=globpath(&rtp, 'ftplugin/ATP_files/compile.py') endif if !exists("g:atp_cpcmd") || g:atp_reload_variables " 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_variables let g:atp_EnvNameTheorem="theorem" endif if !exists("g:atp_EnvNameDefinition") || g:atp_reload_variables let g:atp_EnvNameDefinition="definition" endif if !exists("g:atp_EnvNameProposition") || g:atp_reload_variables let g:atp_EnvNameProposition="proposition" endif if !exists("g:atp_EnvNameObservation") || g:atp_reload_variables " 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_variables let g:atp_EnvNameLemma="lemma" endif if !exists("g:atp_EnvNameNote") || g:atp_reload_variables let g:atp_EnvNameNote="note" endif if !exists("g:atp_EnvNameCorollary") || g:atp_reload_variables let g:atp_EnvNameCorollary="corollary" endif if !exists("g:atp_EnvNameRemark") || g:atp_reload_variables let g:atp_EnvNameRemark="remark" endif if !exists("g:atp_EnvOptions_enumerate") || g:atp_reload_variables " 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_variables " Similar to g:atp_enumerate_options. let g:atp_EnvOptions_itemize="" endif if !exists("g:atp_VimCompatible") || g:atp_reload_variables " 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_variables " 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_variables " Used by :SshPrint let g:atp_lprcommand = "lpr" endif if !exists("g:atp_iabbrev_leader") || g:atp_reload_variables " Used for abbreviations: =theorem= (from both sides). let g:atp_iabbrev_leader = "=" endif if !exists("g:atp_bibrefRegister") || g:atp_reload_variables " 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_variables 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_variables let g:atpbib_WgetOutputFile = "amsref.html" endif if !exists("g:atpbib_wget") || g:atp_reload_variables let g:atpbib_wget="wget" endif if !exists("g:atp_vmap_text_font_leader") || g:atp_reload_variables let g:atp_vmap_text_font_leader="" endif if !exists("g:atp_vmap_environment_leader") || g:atp_reload_variables let g:atp_vmap_environment_leader="" endif if !exists("g:atp_vmap_bracket_leader") || g:atp_reload_variables let g:atp_vmap_bracket_leader="" endif if !exists("g:atp_vmap_big_bracket_leader") || g:atp_reload_variables let g:atp_vmap_big_bracket_leader='b' endif if !exists("g:atp_map_forward_motion_leader") || g:atp_reload_variables let g:atp_map_forward_motion_leader='>' endif if !exists("g:atp_map_backward_motion_leader") || g:atp_reload_variables let g:atp_map_backward_motion_leader='<' endif if !exists("g:atp_RelativePath") || g:atp_reload_variables " 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_variables let g:atp_SyncXpdfLog = 0 endif if !exists("g:atp_LogSync") || g:atp_reload_variables 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 "[ATP:] 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_variables " Use b:changedtick variable to run s:Compiler automatically. let g:atp_Compare = "changedtick" endif if !exists("g:atp_babel") || g:atp_reload_variables let g:atp_babel = 0 endif " if !exists("g:atp_closebracket_checkenv") || g:atp_reload_variables " 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:/ endtry " endif " if !exists("g:atp_ProjectScript") || g:atp_reload_variables " let g:atp_ProjectScript = 1 " endif if !exists("g:atp_OpenTypeDict") || g:atp_reload_variables 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_variables let g:atp_LibraryPath = 0 endif if !exists("g:atp_statusOutDir") || g:atp_reload_variables let g:atp_statusOutDir = 1 endif if !exists("g:atp_developer") || g:atp_reload_variables let g:atp_developer = 0 endif if !exists("g:atp_mapNn") || g:atp_reload_variables 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_variables let g:atp_TeXdocDefault = '-a -I lshort' endif "ToDo: to doc. "ToDo: luatex! (can produce both!) if !exists("g:atp_CompilersDict") || g:atp_reload_variables 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_variables 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_variables let g:ViewerMsg_Dict = { \ 'xpdf' : 'Xpdf', \ 'xdvi' : 'Xdvi', \ 'kpdf' : 'Kpdf', \ 'okular' : 'Okular', \ 'evince' : 'Evince', \ 'acroread' : 'AcroRead', \ 'epdfview' : 'epdfView' } endif if !exists("g:atp_updatetime_insert") || g:atp_reload_variables let g:atp_updatetime_insert = 2000 endif if !exists("g:atp_updatetime_normal") || g:atp_reload_variables let g:atp_updatetime_normal = 1000 endif if g:atp_updatetime_normal let &l:updatetime=g:atp_updatetime_normal endif if !exists("g:atp_DefaultDebugMode") || g:atp_reload_variables " recognised values: silent, debug. let g:atp_DefaultDebugMode = "silent" endif if !exists("g:atp_show_all_lines") || g:atp_reload_variables " boolean let g:atp_show_all_lines = 0 endif if !exists("g:atp_ignore_unmatched") || g:atp_reload_variables " boolean let g:atp_ignore_unmatched = 1 endif if !exists("g:atp_imap_first_leader") || g:atp_reload_variables let g:atp_imap_first_leader = "#" endif if !exists("g:atp_imap_second_leader") || g:atp_reload_variables let g:atp_imap_second_leader= "##" endif if !exists("g:atp_imap_third_leader") || g:atp_reload_variables let g:atp_imap_third_leader = "]" endif if !exists("g:atp_imap_fourth_leader") || g:atp_reload_variables let g:atp_imap_fourth_leader= "[" endif " todo: to doc. if !exists("g:atp_completion_font_encodings") || g:atp_reload_variables 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_variables 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_variables 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_variables let g:atp_algorithmic_dict = { 'IF' : 'ENDIF', 'FOR' : 'ENDFOR', 'WHILE' : 'ENDWHILE' } endif if !exists("g:atp_bracket_dict") || g:atp_reload_variables let g:atp_bracket_dict = { '(' : ')', '{' : '}', '[' : ']', '\lceil' : '\rceil', '\lfloor' : '\rfloor', '\langle' : '\rangle', '\lgroup' : '\rgroup' } endif if !exists("g:atp_LatexBox") || g:atp_reload_variables let g:atp_LatexBox = 1 endif if !exists("g:atp_check_if_LatexBox") || g:atp_reload_variables let g:atp_check_if_LatexBox = 1 endif if !exists("g:atp_autex_check_if_closed") || g:atp_reload_variables let g:atp_autex_check_if_closed = 1 endif if !exists("g:atp_env_maps_old") || g:atp_reload_variables let g:atp_env_maps_old = 0 endif if !exists("g:atp_amsmath") || g:atp_reload_variables let g:atp_amsmath=atplib#SearchPackage('ams') endif if atplib#SearchPackage('amsmath') || g:atp_amsmath != 0 || atplib#DocumentClass(b:atp_MainFile) =~ '^ams' exe "setlocal complete+=k".globpath(&rtp, "ftplugin/ATP_files/dictionaries/ams_dictionary") endif if !exists("g:atp_no_math_command_completion") || g:atp_reload_variables let g:atp_no_math_command_completion = 0 endif if !exists("g:atp_tex_extensions") || g:atp_reload_variables let g:atp_tex_extensions = ["tex.project.vim", "aux", "log", "bbl", "blg", "bcf", "run.xml", "spl", "snm", "nav", "thm", "brf", "out", "toc", "mpx", "idx", "ind", "ilg", "maf", "glo", "mtc[0-9]", "mtc1[0-9]", "pdfsync", "synctex.gz" ] endif for ext in g:atp_tex_extensions let suffixes = split(&suffixes, ",") if index(suffixes, ".".ext) == -1 exe "setlocal suffixes+=.".ext endif endfor if !exists("g:atp_delete_output") || g:atp_reload_variables let g:atp_delete_output = 0 endif if !exists("g:keep") || g:atp_reload_variables let g:keep=[ "log", "aux", "toc", "bbl", "ind", "synctex.gz", "blg", "loa", "toc", "lot", "lof", "thm" ] " biber stuff is added before compelation, this makes it possible to change " to biber on the fly if b:atp_BibCompiler =~ '^\s*biber\>' let g:keep += [ "run.xml", "bcf" ] endif endif if !exists("g:atp_ssh") || g:atp_reload_variables " WINDOWS NOT COMPATIBLE let g:atp_ssh=$USER . "@localhost" endif " opens bibsearch results in vertically split window. if !exists("g:vertical") || g:atp_reload_variables let g:vertical = 1 endif if !exists("g:matchpair") || g:atp_reload_variables let g:matchpair="(:),[:],{:}" endif if !exists("g:texmf") || g:atp_reload_variables let g:texmf = $HOME . "/texmf" endif if !exists("g:atp_compare_embedded_comments") || g:atp_reload_variables || 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_variables || 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("g:atp_toc_window_width") || g:atp_reload_variables let g:atp_toc_window_width = 30 endif if !exists("t:toc_window_width") || g:atp_reload_variables let t:toc_window_width = g:atp_toc_window_width endif if !exists("t:atp_labels_window_width") || g:atp_reload_variables 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_variables let g:atp_completion_limits = [40,60,80,120] endif if !exists("g:atp_long_environments") || g:atp_reload_variables let g:atp_long_environments = [] endif if !exists("g:atp_no_complete") || g:atp_reload_variables let g:atp_no_complete = ['document'] endif " if !exists("g:atp_close_after_last_closed") || g:atp_reload_variables " let g:atp_close_after_last_closed=1 " endif if !exists("g:atp_no_env_maps") || g:atp_reload_variables let g:atp_no_env_maps = 0 endif if !exists("g:atp_extra_env_maps") || g:atp_reload_variables 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_variables " let g:atp_math_commands_first=1 " endif if !exists("g:atp_completion_truncate") || g:atp_reload_variables 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_variables 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_variables " User - highlight status notifications with highlight group User. let g:atp_statusNotifHi = 0 endif if !exists("g:atp_callback") || g:atp_reload_variables if exists("g:atp_statusNotif") && g:atp_statusNotif == 1 && \ 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_variables " let g:atp_complete_math_env_first=0 " endif " }}} " " Project Settings: " {{{1 if !exists("g:atp_ProjectLocalVariables") || g:atp_reload_variables " 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", \ "b:TreeOfFiles", "b:ListOfFiles", "b:TypeDict", \ "b:LevelDict", "b:atp_BibCompiler" \ ] 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 cmd = "let " . var . "=" . string(a:variables_Dict[var]) try exe cmd catch E741: "if the variable was locked exe "unlockvar ".var exe cmd exe "lockvar ".var endtry 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)")) redraw echohl WarningMsg echo "Local buffer variables:" echohl Normal 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.string(getbufvar(bufnr(""), key)) " endif endif endfor if a:bang == "!" " Show some global options echo "\n" echohl WarningMsg echo "Global variables (defined in ".s:file."):" echohl Normal 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 if index(["g:atp_LatexPackages", "g:atp_LatexClasses", "g:optionsDict", "g:optionsKeys", "g:atp_completion_modes", "g:atp_completion_modes_normal_mode", "g:atp_Environments", "g:atp_shortname_dict", "g:atp_MathTools_environments", "g:atp_keymaps", "g:atp_CupsOptions", "g:atp_CompilerMsg_Dict", "g:ViewerMsg_Dict", "g:CompilerMsg_Dict", "g:atp_amsmath_environments"], var_name) == -1 && var_name !~# '^g:atp_Beamer' && var_name !~# '^g:atp_TodoNotes' echo var_name.space.string({var_name}) if len(var_name.space.string({var_name})) > &l:columns echo "\n" endif endif " 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 if !exists("t:atp_QuickFixOpen") let t:atp_QuickFixOpen = 0 endif 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_variables 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" if exists("g:atp_xdviOptions") let g:atp_xdviOptions += index(g:atp_xdviOptions, '-editor') != -1 && \ ( !exists("b:atp_xdviOptions") || exists("b:atp_xdviOptions") && index(b:atp_xdviOptions, '-editor') != -1 ) \ ? ["-editor", "'".v:progname." --servername ".v:servername." --remote-wait +%l %f'"] : [] else let g:atp_xdviOptions = ["-editor", "'".v:progname." --servername ".v:servername." --remote-wait +%l %f'"] endif 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 || g:atp_reload_functions " {{{ 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 "[ATP:] 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 "[ATP:] 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 "[ATP:] 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 "[ATP:] 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 function! ATP_CmdwinToggleSpace(on) let on = ( a:0 >=1 ? ( a:1 == 'on' ? 1 : 0 ) : maparg('', 'i') == "" ) let g:on = on if on echomsg "space ON" imap \_s\+ else echomsg "space OFF" iunmap 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 "[ATP:] 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 "[ATP:] 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 "[ATP:] 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 "[ATP:] 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(mode,...) if a:mode != "" let set_new = 1 let new_debugmode = ( t:atp_DebugMode ==# a:mode ? g:atp_DefaultDebugMode : a:mode ) let copen = ( a:mode =~? '^d\%[ebug]' && t:atp_DebugMode !=? 'debug' && !t:atp_QuickFixOpen ) let on = ( a:mode !=# t:atp_DebugMode ) if t:atp_DebugMode ==# 'Debug' && a:mode ==# 'debug' || t:atp_DebugMode ==# 'debug' && a:mode ==# 'Debug' let change_menu = 0 else let change_menu = 1 endif else let change_menu = 1 let new_debugmode = "" if a:0 >= 1 && a:1 =~ '^on\|off$' let [ on, new_debugmode ] = ( a:1 == 'on' ? [ 1, 'debug' ] : [0, g:atp_DefaultDebugMode] ) let set_new=1 let copen = 1 elseif a:0 >= 1 let t:atp_DebugMode = a:1 let new_debugmode = a:1 let set_new = 0 if a:1 =~ 's\%[ilent]' let on = 0 let copen = 0 elseif a:1 =~ '^d\%[ebug]' let on = 1 let copen = ( a:1 =~# '^D\%[ebug]' ? 1 : 0 ) else " for verbose mode let on = 0 let copen = 0 endif else let set_new = 1 let [ on, new_debugmode ] = ( t:atp_DebugMode =~? '^\%(debug\|verbose\)$' ? [ 0, g:atp_DefaultDebugMode ] : [ 1, 'debug' ] ) let copen = 1 endif endif " let g:on = on " let g:set_new = set_new " let g:new_debugmode = new_debugmode " let g:copen = copen " let g:change_menu = change_menu " on == 0 set debug off " on == 1 set debug on if !on echomsg "[ATP debug mode:] ".new_debugmode if change_menu 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]ToggleDebugMode \ :ToggleDebugMode cmenu 550.20.5 &LaTeX.&Log.Toggle\ &Debug\ Mode\ [off]ToggleDebugMode \ ToggleDebugMode imenu 550.20.5 &LaTeX.&Log.Toggle\ &Debug\ Mode\ [off]ToggleDebugMode \ :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 endif if set_new let t:atp_DebugMode = new_debugmode endif silent cclose else echomsg "[ATP debug mode:] ".new_debugmode if change_menu 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]ToggleDebugMode \ :ToggleDebugMode cmenu 550.20.5 &LaTeX.&Log.Toggle\ &Debug\ Mode\ [on]ToggleDebugMode \ ToggleDebugMode imenu 550.20.5 &LaTeX.&Log.Toggle\ &Debug\ Mode\ [on]ToggleDebugMode \ :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 endif let g:atp_callback = 1 if set_new let t:atp_DebugMode = new_debugmode endif let winnr = bufwinnr("%") if copen let efm=b:atp_ErrorFormat exe "ErrorFormat ".efm silent! cg if len(getqflist()) > 0 exe "silent copen ".min([atplib#qflength(), g:atp_DebugModeQuickFixHeight]) exe winnr . " wincmd w" else echo "[ATP:] no errors for b:atp_ErrorFormat=".efm endif endif endif endfunction function! ToggleDebugModeCompl(A,B,C) return "silent\ndebug\nDebug\nverbose\non\noff" 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 '[ATP:] map OFF' else imap =atplib#TabCompletion(1) echo '[ATP:] map ON' endif endif endfunction " }}} " {{{ ATP_ToggleIMaps " switches on/off the map for TabCompletion function! ATP_ToggleMathIMaps(insert_enter, bang,...) " let g:arg = ( a:0 >=1 ? a:1 : 0 ) " let g:bang = a:bang let on = ( a:0 >=1 ? ( a:1 == 'on' ? 1 : 0 ) : g:atp_imap_define_math <= 0 || g:atp_imap_define_math_misc <= 0 ) " let g:debug=g:atp_imap_define_math." ".g:atp_imap_define_math_misc " let g:on = on " echomsg "****" " echomsg g:arg " echomsg g:debug " echomsg g:on if on == 0 " echomsg "DELETE IMAPS" let g:atp_imap_define_math = ( a:bang == "!" ? -1 : 0 ) call atplib#DelMaps(g:atp_imap_math) let g:atp_imap_define_math_misc = ( a:bang == "!" ? -1 : 0 ) call atplib#DelMaps(g:atp_imap_math_misc) echo '[ATP:] imaps OFF '.(a:bang == "" ? '(insert)' : '') else " echomsg "MAKE IMAPS" let g:atp_imap_define_math =1 call atplib#MakeMaps(g:atp_imap_math) let g:atp_imap_define_math_misc = 1 call atplib#MakeMaps(g:atp_imap_math_misc) echo '[ATP:] imaps ON' endif " Setting eventignore is not a good idea " (this might break specific user settings) " if a:insert_enter " let g:atp_eventignore=&l:eventignore " let g:atp_eventignoreInsertEnter=1 " set eventignore+=InsertEnter " " " This doesn't work because startinsert runs after function ends. " endif endfunction " }}} endif " Commands And Maps: command! -buffer -nargs=? -complete=customlist,atplib#OnOffComp ToggleMathIMaps :call ATP_ToggleMathIMaps(0, "!", ) nnoremap ToggleMathIMaps :call ATP_ToggleMathIMaps(0, "!") inoremap ToggleMathIMaps :call ATP_ToggleMathIMaps(0, "!") " inoremap ToggleMathIMaps :call ATP_ToggleMathIMaps(1, "") 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() nnoremap ToggleSpaceOn :call ATP_ToggleSpace('on') nnoremap ToggleSpaceOff :call ATP_ToggleSpace('off') 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=custom,ToggleDebugModeCompl ToggleDebugMode :call ATP_ToggleDebugMode("",) nnoremap ToggledebugMode :call ATP_ToggleDebugMode("debug") nnoremap ToggleDebugMode :call ATP_ToggleDebugMode("Debug") 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_variables unlockvar g:atp_completion_modes_normal_mode 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_variables let g:atp_completion_active_modes=deepcopy(g:atp_completion_modes) endif if !exists("g:atp_completion_active_modes_normal_mode") || g:atp_reload_variables 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_variables 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', 'frame' ] 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_variables let g:atp_separator=':' endif if !exists("g:atp_no_separator") || g:atp_reload_variables let g:atp_no_separator = 0 endif if !exists("g:atp_no_short_names") || g:atp_reload_variables 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", \ "\hfil", "\\hfill", "\\hspace","\\hline", \ "\\large", "\\Large", "\\LARGE", "\\huge", "\\HUGE", \ "\\overline{", "\\underline{", \ "\\usefont{", "\\fontsize{", "\\selectfont", "\\fontencoding{", "\\fontfamiliy{", "\\fontseries{", "\\fontshape{", \ "\\rmdefault", "\\sfdefault", "\\ttdefault", "\\bfdefault", "\\mddefault", "\\itdefault", \ "\\sldefault", "\\scdefault", "\\updefault", "\\renewcommand{", "\\newcommand{", \ "\\input", "\\include", "\\includeonly", "\\includegraphics", \ "\\savebox", "\\sbox", "\\usebox", "\\rule", "\\raisebox{", \ "\\parbox{", "\\mbox{", "\\makebox{", "\\framebox{", "\\fbox{", \ "\\medskip", "\\smallskip", "\\vskip", "\\vfil", "\\vfill", "\\vspace{", "\\vbox", \ "\\hrulefill", "\\dotfill", "\\hbox", \ "\\thispagestyle{", "\\mathnormal", "\\markright{", "\\markleft{", "\\pagestyle{", "\\pagenumbering{", \ "\\author{", "\\address{", "\\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{", \ "\\signature{", "\\stopbreaks", "\\startbreaks", \ "\\newcounter{", "\\refstepcounter{", \ "\\roman{", "\\Roman{", "\\stepcounter{", "\\setcounter{", \ "\\usecounter{", "\\value{", \ "\\newlength{", "\\setlength{", "\\addtolength{", "\\settodepth{", "\\nointerlineskip", \ "\\addcontentsline{", "\\addtocontents", \ "\\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(" ] let g:atp_hyperref_commands=[ '\hypersetup{', '\hypertarget{', '\url{', '\nolinkurl{', '\hyperbaseurl{', \ '\hyperdef{', '\hyperref', '\hyperlink{', '\phantomsection', '\autoref{', '\autopageref{', \ '\ref*{', '\autoref*{', '\autopageref*{', '\pdfstringdef{', '\pdfbookmark', \ '\curretnpdfbookmark{', '\subpdfbookmark{', '\subpdfbookmark{', '\belowpdfbookmark{', \ '\texorpdfstring{', '\hypercalcbp', '\Acrobatmenu{', \ '\textField', '\CheckBox', '\ChoiceMenu', '\PushButton', '\Submit', '\Reset', \ '\LayoutTextField', '\LayoutChoiceField', '\LayoutCheckField', '\MakeRadioField{', \ '\MakeCheckField{', '\MakeTextField{', '\MakeChoiceField{', '\MakeButtonField{' ] " 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", "\\infty", "\\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", "\\cdot", "\\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_variables 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{", \ "\\pause", "\\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' ] "Todo: PackageOptions are not yet done. let g:atp_TodoNotes_packageOptions = [ 'textwidth', 'textsize', \ 'prependcaption', 'shadow', 'dvistyle', 'figwidth', 'obeyDraft' ] let g:atp_TodoNotes_missingfigure_options = [ 'figwidth=' ] if !exists("g:atp_MathOpened") || g:atp_reload_variables 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' ] " }}} " " AUTOCOMMANDS: " Some of the autocommands (Status Line, LocalCommands, Log File): " {{{ Autocommands: if !s:did_options augroup ATP_UpdateToCLine au! au CursorHold *.tex nested :call UpdateToCLine() augroup END function! RedrawToC() if bufwinnr(bufnr("__ToC__")) != -1 let winnr = winnr() TOC exe winnr." wincmd w" endif endfunction augroup ATP_TOC_tab au! au TabEnter *.tex :call RedrawToC() augroup END let g:atp_eventignore = &l:eventignore let g:atp_eventignoreInsertEnter = 0 function! InsertLeave_InsertEnter() if g:atp_eventignoreInsertEnter setl eventignore-=g:atp_eventignore endif endfunction augroup ATP_InsertLeave_eventignore " ToggleMathIMaps au! au InsertLeave *.tex :call InsertLeave_InsertEnter() augroup END augroup ATP_Cmdwin au! au CmdwinLeave / :call ATP_CmdwinToggleSpace(0) au CmdwinLeave ? :call ATP_CmdwinToggleSpace(0) augroup END augroup ATP_cmdheight " update g:atp_cmdheight when user writes the buffer au! au BufWrite *.tex :let g:atp_cmdheight = &l:cmdheight augroup END function! Rmdir(dir) if executable("rmdir") call system("rmdir ".shellescape(a:dir)) elseif has("python") && executable(g:atp_Python) python << EOF import shutil, errno dir=vim.eval('a:dir') try: shutil.rmtree(dir) except OSError, e: if errno.errorcode[e.errno] == 'ENOENT': pass EOF else echohl ErrorMsg echo "[ATP:] the directory ".a:dir." is not removed." echohl Normal endif endfunction function! ErrorMsg(type) let errors = len(filter(getqflist(),"v:val['type']==a:type")) let type = (a:type == 'E' ? 'errors' : 'warnnings') let msg = "" if errors let msg.=" ".errors." ".type endif return msg endfunction augroup ATP_QuickFix_2 au! au FileType qf command! -bang -buffer -nargs=? -complete=custom,DebugComp DebugMode :call SetDebugMode(,) au FileType qf let w:atp_qf_errorfile=&l:errorfile au FileType qf setl statusline=%{w:atp_qf_errorfile}%=\ %#WarnningMsg#%{ErrorMsg('W')}\ %#ErrorMsg#%{ErrorMsg('E')} au FileType qf exe "resize ".min([atplib#qflength(), g:atp_DebugModeQuickFixHeight]) augroup END function! BufEnterCgetfile() if g:atp_cgetfile try cgetfile " cgetfile needs: exe "ErrorFormat ".b:atp_ErrorFormat catch /E40:/ endtry endif endfunction augroup ATP_QuickFix_cgetfile au! au BufEnter *.tex :call BufEnterCgetfile() augroup END augroup ATP_VimLeave au! " Remove b:atp_TempDir (where compelation is done). au VimLeave *.tex :call Rmdir(b:atp_TempDir) " Remove TempDir for debug files. au VimLeave *.tex :call RmTempDir() " :Kill! (i.e. silently if there is no python support.) au VimLeave *.tex :Kill! augroup END function! UpdateTime(enter) if a:enter == "Enter" && g:atp_updatetime_insert != 0 let &l:updatetime = g:atp_updatetime_insert elseif a:enter == "Leave" && g:atp_updatetime_normal != 0 let &l:updatetime = g:atp_updatetime_normal endif endfunction augroup ATP_UpdateTime au! au InsertEnter *.tex :call UpdateTime("Enter") au InsertLeave *.tex :call UpdateTime("Leave") 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 ! " 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 " 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_variables let g:atp_SetMathVimOptions = 1 endif if !exists("g:atp_MathVimOptions") || g:atp_reload_variables " { 'option_name' : [ val_in_math, normal_val], ... } let g:atp_MathVimOptions = { 'textwidth' : [ 0, &textwidth], \ } endif if !exists("g:atp_MathZones") || g:atp_reload_variables 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() " add texMathZoneT syntax group for tikzpicture environment: if atplib#SearchPackage('tikz') || atplib#SearchPackage('pgfplots') try call TexNewMathZone("T", "tikzpicture", 0) catch /E117:/ endtry endif " add texMathZoneALG syntax group for algorithmic environment: if atplib#SearchPackage('algorithmic') try call TexNewMathZone("ALG", "algorithmic", 0) catch /E117:/ endtry endif endfunction augroup ATP_AddSyntaxGroups 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! Viewer(...) if a:0 == 0 || a:1 =~ '^\s*$' echomsg "[ATP:] current viewer: ".b:atp_Viewer return else let new_viewer = a:1 endif let old_viewer = b:atp_Viewer let oldViewer = get(g:ViewerMsg_Dict, matchstr(old_viewer, '^\s*\zs\S*'), "") let b:atp_Viewer = new_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=? -complete=customlist,ViewerComp Viewer :call Viewer() function! ViewerComp(A,L,P) let view = [ 'okular', 'xpdf', 'xdvi', 'evince', 'epdfview', 'kpdf', 'acroread', 'zathura', 'gv', \ 'AcroRd32.exe', 'sumatrapdf.exe' ] " The names of Windows programs (second line) might be not right [sumatrapdf.exe (?)]. call filter(view, "v:val =~ '^' . a:A") call filter(view, 'executable(v:val)') return view endfunction function! Compiler(...) if a:0 == 0 echo "[ATP:] b:atp_TexCompiler=".b:atp_TexCompiler return else let compiler = a:1 let old_compiler = b:atp_TexCompiler let oldCompiler = get(g:CompilerMsg_Dict, matchstr(old_compiler, '^\s*\zs\S*'), "") let b:atp_TexCompiler = 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" endif endfunction command! -buffer -nargs=? -complete=customlist,CompilerComp Compiler :call Compiler() function! CompilerComp(A,L,P) let compilers = [ 'tex', 'pdftex', 'latex', 'pdflatex', 'etex', 'xetex', 'luatex', 'xelatex' ] " let g:compilers = copy(compilers) call filter(compilers, "v:val =~ '^' . a:A") call filter(compilers, 'executable(v:val)') return compilers endfunction function! SetDebugMode(bang,...) if a:0 == 0 echo t:atp_DebugMode return else if a:1 =~# '^s\%[silent]' let t:atp_DebugMode= 'silent' elseif a:1 =~# '^d\%[debug]' let t:atp_DebugMode= 'debug' elseif a:1 =~# '^D\%[debug]' let t:atp_DebugMode= 'Debug' elseif a:1 =~# '^v\%[erbose]' let t:atp_DebugMode= 'verbose' else let t:atp_DebugMode= g:atp_DefaultDebugMode endif endif if t:atp_DebugMode ==# 'Debug' && a:1 ==# 'debug' || t:atp_DebugMode ==# 'debug' && a:1 ==# 'Debug' let change_menu = 0 else let change_menu = 1 endif "{{{ Change menu if change_menu && t:atp_DebugMode !=? 'debug' 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]ToggleDebugMode \ :ToggleDebugMode cmenu 550.20.5 &LaTeX.&Log.Toggle\ &Debug\ Mode\ [off]ToggleDebugMode \ ToggleDebugMode imenu 550.20.5 &LaTeX.&Log.Toggle\ &Debug\ Mode\ [off]ToggleDebugMode \ :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 elseif change_menu 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]ToggleDebugMode \ :ToggleDebugMode cmenu 550.20.5 &LaTeX.&Log.Toggle\ &Debug\ Mode\ [on]ToggleDebugMode \ ToggleDebugMode imenu 550.20.5 &LaTeX.&Log.Toggle\ &Debug\ Mode\ [on]ToggleDebugMode \ :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 endif "}}} if a:1 =~# 's\%[ilent]' let winnr=winnr() if t:atp_QuickFixOpen cclose else try cgetfile catch /E40/ echohl WarningMsg echo "[ATP:] log file missing." echohl Normal endtry if a:bang == "!" exe "cwindow " . (max([1, min([len(getqflist()), g:atp_DebugModeQuickFixHeight])])) exe winnr . "wincmd w" endif endif elseif a:1 =~# 'd\%[ebug]' let winnr=winnr() exe "copen " . (!exists("w:quickfix_title") \ ? (max([1, min([atplib#qflength(), g:atp_DebugModeQuickFixHeight])])) \ : "" ) exe winnr . "wincmd w" try cgetfile catch /E40/ echohl WarningMsg echo "[ATP:] log file missing." echohl Normal endtry " DebugMode is not changing when log file is missing! elseif a:1 =~# 'D\%[ebug]' let winnr=winnr() exe "copen " . (!exists("w:quickfix_title") \ ? (max([1, min([atplib#qflength(), g:atp_DebugModeQuickFixHeight])])) \ : "" ) exe winnr . "wincmd w" try cgetfile catch /E40/ echohl WarningMsg echo "[ATP:] log file missing." echohl Normal endtry try cc catch E42: echo "[ATP:] no errors." endtry endif endfunction command! -buffer -bang -nargs=? -complete=custom,DebugComp DebugMode :call SetDebugMode(,) function! DebugComp(A,L,P) return "silent\ndebug\nDebug\nverbose" endfunction "}}}1 " Python test if libraries are present " {{{ function! TestPythonLibs() python << END import vim try: import psutil except ImportError: vim.command('echohl ErrorMsg|echomsg "[ATP:] needs psutil python library."') vim.command('echomsg "You can get it from: http://code.google.com/p/psutil/"') test=vim.eval("has('mac')||has('macunix')||has('unix')") if test != str(0): vim.command('echomsg "Falling back to bash"') vim.command("let g:atp_Compiler='bash'") vim.command("echohl Normal") vim.command("echomsg \"If you don't want to see this message (and you are on *nix system)\"") vim.command("echomsg \"put let g:atp_Compiler='bash' in your vimrc or atprc file.\"") vim.command("sleep 2") END endfunction if g:atp_Compiler == "python" if !executable(g:atp_Python) || !has("python") echohl ErrorMsg echomsg "[ATP:] needs: python and python support in vim." echohl Normal if has("mac") || has("macunix") || has("unix") echohl ErrorMsg echomsg "I'm falling back to bash (deprecated)." echohl Normal let g:atp_Compiler = "bash" echomsg "If you don't want to see this message" echomsg "put let g:atp_Compiler='bash' in your vimrc or atprc file." if !has("python") echomsg "You Vim is compiled without pyhon support, some tools might not work." endif sleep 2 endif else call TestPythonLibs() endif endif " }}} "Make g:atp_TempDir, where log files are stored. "{{{ function! TempDir() " Return temporary directory, unique for each user. if has("python") function! ATP_SetTempDir(tmp) let g:atp_TempDir=a:tmp endfunction python << END import tempfile, os USER=os.getenv("USER") tmp=tempfile.mkdtemp(suffix="", prefix="atp_") vim.eval("ATP_SetTempDir('"+tmp+"')") END delfunction ATP_SetTempDir else let g:atp_TempDir=substitute(tempname(), '\d\+$', "atp_debug", '') call mkdir(g:atp_TempDir, "p", 0700) endif endfunction if g:atp_reload_functions == 0 call TempDir() endif "}}} " Remove g:atp_TempDir tree where log files are stored. " {{{ function! RmTempDir() if has("python") && executable(g:atp_Python) python << END import shutil temp=vim.eval("g:atp_TempDir") print(temp) shutil.rmtree(temp) END elseif has("unix") && has("macunix") call system("rm -rf ".shellescape(g:atp_TempDir)) else echohl ErrorMsg echomsg "[ATP:] Leaving temporary directory ".g:atp_TempDir echohl Normal endif endfunction "}}} " vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1 ftplugin/ATP_files/search.vim [[[1 1215 " 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 : '' 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 name=substitute(name, '\(#\d\+\)\+\s*$', '{', '') if name =~ '#\d\+' echo line['text'] echo name endif 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 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 pattern = '\%(\\def\|\\\%(re\)\=newcommand\s*{\=\|\\providecommand\s*{\=\|\\\%(re\)\=newenvironment\s*{\|\\\%(re\)\=newtheorem\s*{\)\s*\\\=\w*\zs'.pattern let g:pattern = pattern 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, pattern) let g:defi_dict = defi_dict if len(defi_dict) > 0 " wipe out the old buffer and open new one instead if bufloaded("DefiSearch") exe "silent bd! " . bufnr("DefiSearch") endif let b:atp_MainFile = expand("%") let b:atp_ProjectDir = expand("%:p:h") setl syntax=tex let defi_list = [] let g:defi_list = defi_list 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 defi_list 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 add(defi_list, '') " call setline(line('$')+1,'') let i+=1 endif while c <= l:range[1]-l:range[0] let line=l:range[0]+c call add(defi_list, ifile[line-1]) " call setline(line('$')+1,ifile[line-1]) let i+=1 let c+=1 endwhile endif endfor endfor if len(defi_list) == 0 redraw echohl ErrorMsg echomsg "[ATP:] definition not found." echohl Normal return endif let window_height= min([g:atp_DefiSearchMaxWindowHeight, len(defi_list)]) " open new buffer let openbuffer=" +setl\\ buftype=nofile\\ nospell " . fnameescape("DefiSearch") if g:vertical ==1 let openbuffer="keepalt vsplit " . openbuffer else let openbuffer="keepalt rightbelow ".window_height."split " . openbuffer endif silent exe openbuffer call setline(1, defi_list) call matchadd('Search', ( &l:ignorecase ? '\c' : '\C' ) .pattern) let @/=pattern setl ft=tex setl readonly map q :bd else redraw echohl ErrorMsg echomsg "[ATP:] 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 exe "redir! > ".g:atp_TempDir."/SearchInTree.log" 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 = 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 else for new_branch in keys(branch) call SearchInTree(branch, new_branch, whatArg) endfor endif if g:atp_debugSIT redir END endif return 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 exe "redir! > ".g:atp_TempDir."/RecursiveSearch.log" else exe "redir! >> ".g:atp_TempDir."/RecursiveSearch.log" 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 "[ATP:] 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_ProjectLocalVariables") " 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 exe "redir! >> ".g:atp_TempDir."/RecursiveSearch.log" 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 "[ATP:] 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_ProjectLocalVariables") " 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 "[ATP:] 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 "[ATP:] 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') if pattern == "" echohl ErrorMsg echomsg "[ATP:] 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 "[ATP:] 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:] 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 exe "redir! > ".g:atp_TempDir."/Bibsearch.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 2355 " 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 May 08 07: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 "}}} " WrapEnvironment "{{{ " a:1 = 0 (or not present) called by a command " a:1 = 1 called by a key map (ask for env) function! WrapEnvironment(env_name,...) let map = ( a:0 == 0 ? 0 : a:1 ) if !map '<,'>WrapSelection '\begin{'.a:env_name.'}','\end{'.a:env_name.'}','0', '1' else let envs=sort(filter(EnvCompletion("","",""), "v:val !~ '\*$' && v:val != 'thebibliography'")) let g:envs=envs " adjust the list - it is too long. let envs_a=copy(envs) call map(envs_a, "index(envs_a, v:val)+1.'. '.v:val") for line in atplib#PrintTable(envs_a,3) echo line endfor let envs_a=['Which environment to use:']+envs_a let env=input("Which environment to use? type number and press or type environemnt name, to complete, for exit:\n","","customlist,EnvCompletion") let g:env=env if env == "" return elseif env =~ '^\d\+$' let env_name=get(envs, env-1, '') if env_name == '' return endif else let env_name=env endif '<,'>WrapSelection '\begin{'.env_name.'}','\end{'.env_name.'}','0', '1' endif endfunction "}}} vmap WrapEnvironment :call WrapEnvironment('', 1) " 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\|thebibliography\)\s*}', '', '\\end\s*{\s*\%(enumerate\|itemize\|thebibliography\)\s*}', 'bnW') let saved_pos = getpos(".") call cursor(line("."), 1) if g:atp_debugInsertItem let g:debugInsertItem_redir= "redir! > ".g:atp_TempDir."/InsertItem.log" exe "redir! > ".g:atp_TempDir."/InsertItem.log" endif if getline(begin_line) =~ '\\begin\s*{\s*thebibliography\s*}' call cursor(saved_pos[1], saved_pos[2]) let new_line = strpart(getline("."), 0, col(".")) . '\bibitem' . strpart(getline("."), col(".")) call setline(line("."), new_line) " Indent the line: if &l:indentexpr != "" let v:lnum=saved_pos[1] 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*', '', '')) let saved_pos[2] += len('\bibitem') + indent call cursor(saved_pos[1], saved_pos[2]) if g:atp_debugInsertItem let g:InsertIntem_return = 0 silent echo "0] return" redir END endif return endif " This will work with \item [[1]], but not with \item [1]] let [ bline, bcol] = searchpos('\\item\s*\zs\[', 'b', begin_line) if bline == 0 call cursor(saved_pos[1], saved_pos[2]) 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 != "" let v:lnum=saved_pos[1] 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 if g:atp_debugInsertItem silent echo "1] indent=".len(ind) endif call setline(line("."), ind . substitute(getline("."), '^\s*', '', '')) " Set the cursor position let saved_pos[2] += len('\item') + indent keepjumps call setpos(".", saved_pos) if g:atp_debugInsertItem let g:debugInsertItem_return = 1 silent echo "1] return" redir END endif return "" endif let [ eline, ecol] = searchpairpos('\[', '', '\]', 'nr', '', line(".")) if eline != bline if g:atp_debugInsertItem let g:debugInsertItem_return = 2 silent echo "2] return" redir END endif 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, '') if g:atp_debugInsertItem silent echo "(1) new_item=".new_item endif 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') if g:atp_debugInsertItem silent echo "(2) new_item=".new_item endif 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') if g:atp_debugInsertItem silent echo "(3) new_item=".new_item endif 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') if g:atp_debugInsertItem silent echo "(4) new_item=".new_item endif else let new_item = item if g:atp_debugInsertItem silent echo "(5) new_item=".item endif endif keepjumps call setpos(".", saved_pos) let new_line = strpart(getline("."), 0, col(".")) . '\item' . space . '[' . new_item . '] ' . strpart(getline("."), col(".")) if g:atp_debugInsertItem silent echo "new_line=".new_line endif call setline(line("."), new_line) " Indent the line: if &l:indentexpr != "" let v:lnum=saved_pos[1] 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 if g:atp_debugInsertItem silent echo "indent=".len(ind) 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) if g:atp_debugInsertItem let g:debugInsertItem_return = 3 silent echo "3] return" redir END endif 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 "[ATP:] 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 "[ATP:] 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 "[ATP:] 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 "[ATP:] 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 "[ATP:] 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 "}}} function! EnvCompletionWithoutStarEnvs(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 "}}} function! F_compl(ArgLead, CmdLine, CursorPos) "{{{ " This is like EnvCompletion but without stared environments and with: chapter, section, ... 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) let env_list=atplib#Extend(env_list, ['part', 'chapter', 'section', 'subsection', 'subsubsection']) if atplib#SearchPackage('amsmath') let env_list=atplib#Extend(env_list, g:atp_amsmath_environments) endif call filter(env_list+['math'], "v:val !~ '\*$'") return join(env_list, "\n") 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! 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 == "!" || g:atp_delete_output == 1 let ext = substitute(get(g:atp_CompilersDict,b:atp_TexCompiler,""), '^\s*\.', '', 'g') if ext != "" call add(atp_tex_extensions,ext) endif else " filter extensions which should not be deleted call filter(atp_tex_extensions, "index(g:atp_DeleteWithBang, v:val) == -1") endif " Be sure that we are not deleting outputs: for ext in atp_tex_extensions if ext != "pdf" && ext != "dvi" && ext != "ps" let files=split(globpath(fnamemodify(atp_MainFile, ":h"), "*.".ext), "\n") if files != [] echo "Removing *.".ext for f in files call delete(f) endfor endif else " Delete output file (pdf|dvi|ps) (though ps is not supported by ATP). let f=fnamemodify(atplib#FullPath(b:atp_MainFile), ":r").".".ext echo "Removing ".f call delete(f) 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("") let atp_TempDir = b:atp_TempDir exe "rightbelow split +setl\\ nospell\\ ruler\\ syn=log_atp\\ autoread " . fnameescape(&l:errorfile) let b:atp_TempDir = atp_TempDir 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('^[^!].*\n\zs!', 'W') nnoremap [e :call Search('^[^!].*\n\zs!', '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. if g:atp_debugST let g:fname_list = [] endif 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 exe "redir! > ".g:atp_TempDir."/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) " 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 let fname=substitute(fname, escape(fnamemodify(b:atp_TempDir, ":t"), '.').'\/[^\/]*\/', '', '') if g:atp_debugST call add(g:fname_list, fname) let g:fname = fname 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_post = 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 "[ATP:] ".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 "[ATP:] server " . server echomsg "[ATP:] file " . pfile if server =~ 'localhost' let cmd = lprcommand . " " . print_options . " " . fnameescape(pfile) redraw! echomsg "[ATP:] printing ... " . cmd call system(cmd) " " 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 cmd="cat " . fnameescape(pfile) . " | ssh " . g:atp_ssh . " " . lprcommand . " " . print_options call system(cmd) 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 "[ATP:] ".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 cmd = lprcommand . " " . print_options . " " . fnameescape(pfile) redraw! echomsg "[ATP:] printing ... " . cmd call system(cmd) 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 cmd="ssh -q " . g:atp_ssh . " lpstat -a | awk '{print $1}'" else let cmd="lpstat -a | awk '{print $1}'" endif return system(cmd) endfunction function! s:ListLocalPrinters(A,L,P) let cmd="lpstat -a | awk '{print $1}'" return system(cmd) 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 "[ATP:] list for '%.*" . a:keyword . "' in '" . bufname . "' is empty." return endif echomsg "[ATP:] 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) " {{{ ReloadATP " ReloadATP() - reload all the tex_atp functions and delete all autoload functions from " autoload/atplib.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_variables = 0 if a:bang == "" execute "source " . common_file execute "source " . options_file " 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 " Reload all functions and variables, let tex_atp_file = globpath(&rtp, 'ftplugin/tex_atp.vim') execute "source " . tex_atp_file " delete functions from autoload/atplib.vim: let atplib_file = globpath(&rtp, 'autoload/atplib.vim') let saved_loclist = getloclist(0) exe 'lvimgrep /^\s*fun\%[ction]!\=\s\+/gj '.atplib_file let list=map(getloclist(0), 'v:val["text"]') call setloclist(0,saved_loclist) call map(list, 'matchstr(v:val, ''^\s*fun\%[ction]!\=\s\+\zsatplib#\S\+\ze\s*('')') for fname in list if fname != "" exe 'delfunction '.fname endif endfor endif let g:atp_reload_functions = 0 let g:atp_reload_variables = 0 endfunction catch /E127:/ " Cannot redefine function, function is in use. endtry " }}} " 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 "[ATP:] 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') " Get data from AMS web site. let atpbib_WgetOutputFile = tempname() let URLquery_path = globpath(&rtp, 'ftplugin/ATP_files/url_query.py') if a:bibfile != "nobibfile" let url="http://www.ams.org/mathscinet-mref?ref=".what."&dataType=bibtex" else let url="http://www.ams.org/mathscinet-mref?ref=".what."&dataType=tex" endif let cmd=g:atp_Python." ".URLquery_path." ".shellescape(url)." ".shellescape(atpbib_WgetOutputFile) 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)) 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 "[ATP:] 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 "[ATP:] 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 "[ATP:] 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 delete(atpbib_WgetOutputFile) 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 "[ATP:] found bib data is in register " . g:atp_bibrefRegister echohl Normal elseif return[0] == 'NoUniqueMatch' redraw echohl WarningMsg echomsg "[ATP:] 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 "[ATP:] can't open file " . a:new_file return 1 endtry try let old_file = readfile(a:old_file) catch /E484/ echohl ErrorMsg echomsg "[ATP:] 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/\\{=\(\%(=\\}\@!\|=\\\@!}\|=\@!\\}\|[^}=\\]\|=\\\@!\|\\}\@!\|=\@UpdateATP(bang) "DONE: add bang -> get stable/unstable latest release. "DONE: check if the current version is newer than the available one " if not do not download and install (this saves time). if g:atp_debugUpdateATP exe "redir! > ".g:atp_TempDir."/UpdateATP.log" endif let s:ext = "tar.gz" if a:bang == "!" echo "[ATP:] getting list of available snapshots ..." else echo "[ATP:] getting list of available versions ..." endif let s:URLquery_path = globpath(&rtp, 'ftplugin/ATP_files/url_query.py') if a:bang == "!" let url = "http://sourceforge.net/projects/atp-vim/files/snapshots/" else let url = "http://sourceforge.net/projects/atp-vim/files/releases/" endif let url_tempname=tempname()."_ATP.html" let cmd=g:atp_Python." ".s:URLquery_path." ".shellescape(url)." ".shellescape(url_tempname) if g:atp_debugUpdateATP let g:cmd=cmd silent echo "url_tempname=".url_tempname silent echo "cmd=".cmd endif call system(cmd) let saved_loclist = getloclist(0) exe 'lvimgrep /\CCompareStamps") else let sorted_list = sort(keys(dict), "CompareVersions") endif if g:atp_debugUpdateATP silent echo "dict=".string(dict) silent echo "sorted_list=".string(sorted_list) endif "NOTE: this list might contain one item two times (I'm not filtering well the " html sourcefore web page, but this is faster) let dir = fnamemodify(globpath(&rtp, "ftplugin/tex_atp.vim"), ":h:h") if dir == "" echoerr "[ATP:] Cannot find local .vim directory." if g:atp_debugUpdateATP redir END endif return endif " Stamp of the local version let saved_loclist = getloclist(0) if a:bang == "!" try exe '1lvimgrep /\C^"\s*Time\s\+Stamp:/gj '. globpath(&rtp, "ftplugin/tex_atp.vim") let old_stamp = get(getloclist(0),0, {'text' : '00-00-00_00-00'})['text'] call setloclist(0, saved_loclist) let old_stamp=matchstr(old_stamp, '^"\s*Time\s\+Stamp:\s*\zs\%(\d\|_\|-\)*\ze') catch /E480:/ let old_stamp="00-00-00_00-00" endtry else try exe '1lvimgrep /(ver\.\=\%[sion]\s\+\d\+\%(\.\d\+\)*\s*)/gj ' . globpath(&rtp, "doc/automatic-tex-plugin.txt") let old_stamp = get(getloclist(0),0, {'text' : '00-00-00_00-00'})['text'] call setloclist(0, saved_loclist) let old_stamp=matchstr(old_stamp, '(ver\.\=\%[sion]\s\+\zs\d\+\%(\.\d\+\)*\ze') catch /E480:/ let old_stamp="0.0" endtry endif if g:atp_debugUpdateATP silent echo "old_stamp=".old_stamp endif function! GetLatestSnapshot(bang,url) " Get latest snapshot/version let url = a:url let s:ATPversion = matchstr(url, 'AutomaticTexPlugin_\zs\d\+\%(\.\d\+\)*\ze\.'.escape(s:ext, '.')) if a:bang == "!" let ATPdate = matchstr(url, 'AutomaticTexPlugin_\d\+\%(\.\d\+\)*.'.escape(s:ext, '.').'.\zs[0-9-_]*\ze') else let ATPdate = "" endif let s:atp_tempname = tempname()."_ATP.tar.gz" if g:atp_debugUpdateATP silent echo "tempname=".s:atp_tempname endif let cmd=g:atp_Python." ".s:URLquery_path." ".shellescape(url)." ".shellescape(s:atp_tempname) let g:get_cmd=cmd if a:bang == "!" echo "[ATP:] getting latest snapshot (unstable version) ..." else echo "[ATP:] getting latest stable version ..." endif if g:atp_debugUpdateATP silent echo "cmd=".cmd endif call system(cmd) endfunction let new_stamp = sorted_list[0] if g:atp_debugUpdateATP silent echo "new_stamp=".new_stamp endif "Compare stamps: " stamp format day-month-year_hour-minute " if o_stamp is >= than n_stamp ==> return let l:return = 1 if a:bang == "!" let compare = CompareStamps(new_stamp, old_stamp) else let compare = CompareVersions(new_stamp, old_stamp) endif if a:bang == "!" if compare == 1 || compare == 0 redraw echomsg "You have the latest UNSTABLE version of ATP." if g:atp_debugUpdateATP redir END endif return endif else if compare == 1 redraw let l:return = input("You have UNSTABLE version of ATP.\nDo you want to DOWNGRADE to the last STABLE release? type yes/no [or y/n] and hit ") let l:return = (l:return !~? '^\s*y\%[es]\s*$') if l:return call delete(s:atp_tempname) redraw if g:atp_debugUpdateATP redir END endif return endif elseif compare == 0 redraw echomsg "You have the latest STABLE version of ATP." call delete(s:atp_tempname) if g:atp_debugUpdateATP redir END endif return endif endif redraw call GetLatestSnapshot(a:bang, dict[sorted_list[0]]) echo "[ATP:] installing ..." call Tar(s:atp_tempname, dir) call delete(s:atp_tempname) exe "helptags " . finddir("doc", dir) ReloadATP redraw! if a:bang == "!" echomsg "[ATP:] updated to version ".s:ATPversion." (snapshot date stamp ".new_stamp.")." echo "See ':help atp-news' for changes!" else echomsg "[ATP:] ".(l:return ? 'updated' : 'downgraded')." to release ".s:ATPversion endif if bufloaded(globpath(&rtp, "doc/automatic-tex-plugin.txt")) || \ bufloaded(globpath(&rtp, "doc/bibtex_atp.txt")) echo "[ATP:] to reload the ATP help files (and see what's new!), close and reopen them." endif endfunction catch E127: endtry function! CompareStamps(new, old) " newer stamp is smaller " vim sort() function puts smaller items first. " new > old => -1 " new = old => 0 " new < old => 1 let new=substitute(a:new, '\.', '', 'g') let old=substitute(a:old, '\.', '', 'g') return ( new == old ? 0 : new > old ? -1 : 1 ) endfunction function! CompareVersions(new, old) " newer stamp is smaller " vim sort() function puts smaller items first. " new > old => -1 " new = old => 0 " new < old => 1 let new=split(a:new, '\.') let old=split(a:old, '\.') let g:new=new let g:old=old let compare = [] for i in range(max([len(new), len(old)])) let nr = (get(new,i,0) < get(old,i,0) ? 1 : ( get(new,i,0) == get(old,i,0) ? 0 : 2 )) call add(compare, nr) endfor let comp = join(compare, "") " comp =~ '^0*1' new is older version return ( comp == 0 ? 0 : ( comp =~ '^0*1' ? 1 : -1 )) " return ( new == old ? 0 : new > old ? -1 : 1 ) endfunction function! GetTimeStamp(file) python << END import vim, tarfile, re file_name =vim.eval('a:file') tar_file =tarfile.open(file_name, 'r:gz') def tex(name): if re.search('ftplugin/tex_atp\.vim', str(name)): return True else: return False member=filter(tex, tar_file.getmembers())[0] pfile=tar_file.extractfile(member) stamp="" for line in pfile.readlines(): if re.match('\s*"\s+Time\s+Stamp:\s+', line): stamp=line break try: match=re.match('\s*"\s+Time\s+Stamp:\s+([0-9\-_]*)', stamp) stamp=match.group(1) except AttributeError: stamp="00-00-00_00-00" vim.command("let g:atp_stamp='"+stamp+"'") END endfunction function! Tar(file,path) python << END import tarfile, vim file_n=vim.eval("a:file") path=vim.eval("a:path") file_o=tarfile.open(file_n, "r:gz") file_o.extractall(path) END endfunction " function! Tar(file,path) " python << END " import tarfile, vim " file_n=vim.eval("a:file") " print(file_n) " path=vim.eval("a:path") " print(path) " file_o=tarfile.open(file_n, "r:gz") " file_o.extractall(path) " END " endfunction function! ATPversion() " This function is used in opitons.vim let saved_loclist = getloclist(0) try exe 'lvimgrep /\C^"\s*Time\s\+Stamp:/gj '. globpath(&rtp, "ftplugin/tex_atp.vim") let stamp = get(getloclist(0),0, {'text' : '00-00-00_00-00'})['text'] let stamp = matchstr(stamp, '^"\s*Time\s\+Stamp:\s*\zs\%(\d\|_\|-\)*\ze') catch /E480:/ let stamp = "(no stamp)" endtry try exe 'lvimgrep /^\C\s*An\s\+Introduction\s\+to\s\+AUTOMATIC\s\+(La)TeX\s\+PLUGIN\s\+(ver\%(\.\|sion\)\=\s\+[0-9.]*)/gj '. globpath(&rtp, "doc/automatic-tex-plugin.txt") let l:version = get(getloclist(0),0, {'text' : 'unknown'})['text'] let l:version = matchstr(l:version, '(ver\.\?\s\+\zs[0-9.]*\ze)') catch /E480:/ let l:version = "(no version number)" endtry call setloclist(0, saved_loclist) redraw let g:atp_version = l:version ." (".stamp.")" return "ATP version: ".l:version.", time stamp: ".stamp."." endfunction "}}} " Comment Lines function! Comment(arg) "{{{ " remember the column of the cursor let col=col('.') if a:arg==1 call setline(line('.'),g:atp_CommentLeader . getline('.')) let l:scol=l:col+len(g:atp_CommentLeader)-4 call cursor(line('.'),l:scol) elseif a:arg==0 && getline('.') =~ '^\s*' . g:atp_CommentLeader call setline(line('.'),substitute(getline('.'),g:atp_CommentLeader,'','')) call cursor(line('.'),l:col-len(g:atp_CommentLeader)) endif endfunction "}}} " DebugPrint " cat files under g:atp_TempDir (with ATP debug info) " {{{ if has("unix") && g:atp_atpdev function! DebugPrint(file) if a:file == "" return endif let dir = getcwd() exe "lcd ".g:atp_TempDir if filereadable(a:file) echo join(readfile(a:file), "\n") else echomsg "No such file." endif exe "lcd ".dir endfunction function! DebugPrintComp(A,C,L) let list = split(globpath(g:atp_TempDir, "*"), "\n") let dir = getcwd() exe "lcd ".g:atp_TempDir call map(list, "fnamemodify(v:val, ':.')") exe "lcd ".dir return join(list, "\n") endfunction command! -nargs=? -complete=custom,DebugPrintComp DebugPrint :call DebugPrint() endif "}}} endif "}}} " COMMANDS AND MAPS: " Maps: "{{{1 map CommentLines :call Comment(1) map UnCommentLines :call Comment(0) vmap 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=? -complete=customlist,EnvCompletion -range WrapEnvironment :call WrapEnvironment() 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() command! -buffer -bang UpadteATP :call UpdateATP() command! -buffer ATPversion :echo ATPversion() " 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:] 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:] 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_begin != "" ? g:atp_imap_third_leader.g:atp_imap_begin." \\begin{} " : "" ).(g:atp_imap_end != "" ? g:atp_imap_third_leader.g:atp_imap_end." \\end{}" : "") \."\n ".(g:atp_imap_theorem != "" ? g:atp_imap_third_leader.g:atp_imap_theorem." theorem " : "" ).(g:atp_imap_definition != "" ? g:atp_imap_third_leader.g:atp_imap_definition." definition" : "") \."\n ".(g:atp_imap_proposition != "" ? g:atp_imap_third_leader.g:atp_imap_proposition." proposition " : "").(g:atp_imap_lemma != "" ? g:atp_imap_third_leader.g:atp_imap_lemma." lemma" : "") \."\n ".(g:atp_imap_remark != "" ? g:atp_imap_third_leader.g:atp_imap_remark." remark " : "").(g:atp_imap_corollary != "" ? g:atp_imap_third_leader.g:atp_imap_corollary." corollary" : "") \."\n ".(g:atp_imap_proof != "" ? g:atp_imap_third_leader.g:atp_imap_proof." proof " : "").(g:atp_imap_example != "" ? g:atp_imap_third_leader.g:atp_imap_example." example" : "") \."\n ".(g:atp_imap_note != "" ? g:atp_imap_third_leader.g:atp_imap_note." note " : "") \."\n" \."\n ".(g:atp_imap_enumerate != "" ? g:atp_imap_third_leader.g:atp_imap_enumerate." enumerate " : "").(g:atp_imap_itemize != "" ? g:atp_imap_third_leader.g:atp_imap_itemize." itemize" : "") \."\n ".(g:atp_imap_item != "" ? g:atp_imap_third_leader.g:atp_imap_item." \\item" : "") \."\n" \.(g:atp_imap_align != "" ? "\n ".g:atp_imap_third_leader.g:atp_imap_align." align " : "").(g:atp_imap_equation != "" ? g:atp_imap_third_leader.g:atp_imap_equation." equation" : "") \."\n" \."\n ".(g:atp_imap_flushleft != "" ? g:atp_imap_third_leader.g:atp_imap_flushleft." flushleft " : "").(g:atp_imap_flushright != "" ? g:atp_imap_third_leader.g:atp_imap_flushright." flushright" : "") \."\n ".(g:atp_imap_center != "" ? g:atp_imap_third_leader.g:atp_imap_center." center" : "") \."\n" \.(g:atp_imap_tikzpicture != "" ? "\n ".g:atp_imap_third_leader.g:atp_imap_tikzpicture." tikzpicture" : "") \."\n" \."\n ".(g:atp_imap_frame != "" ? g:atp_imap_third_leader.g:atp_imap_frame." frame " : "").(g:atp_imap_letter != "" ? g:atp_imap_third_leader.g:atp_imap_letter." letter" : "" ) 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:] 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 54 #!/usr/bin/python # Author: Marcin Szamotulski # This script is a part of Automatic TeX Plugin for Vim. # It can be destributed seprately under General Public Licence ver.3 or higher. # 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 and column . # Column number is an optoinal argument if not set on the command line it is 1. # 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 '%f' '%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, re f = open('/tmp/atp_RevSearch.debug', 'w') # Get list of vim servers. output = subprocess.Popen(["gvim", "--serverlist"], stdout=subprocess.PIPE) servers = output.stdout.read().decode() match=re.match('(.*)(\\\\n)?', servers) # Get the column (it is an optional argument) if (len(sys.argv) >= 4 and int(sys.argv[3]) > 0): column = str(sys.argv[3]) else: column = str(1) f.write(">>> args "+sys.argv[1]+":"+sys.argv[2]+":"+column+"\n") if match != None: servers=match.group(1) server_list=servers.split('\\n') server = server_list[0] # Call atplib#FindAndOpen() cmd="gvim --servername "+server+" --remote-expr \"atplib#FindAndOpen('"+sys.argv[1]+"','"+sys.argv[2]+"','"+column+"')\"" subprocess.call(cmd, shell=True) # Debug: f.write(">>> output "+str(servers)+"\n") if match != None: f.write(">>> file "+sys.argv[1]+"\n>>> line "+sys.argv[2]+"\n>>> column "+column+"\n>>> server "+server+"\n>>> server list "+str(server_list)+"\n>>> cmd "+cmd+"\n") else: f.write(">>> file "+sys.argv[1]+"\n>>> line "+sys.argv[2]+"\n>>> column "+column+"\n>>> server not found\n") f.close() ftplugin/ATP_files/compile.py [[[1 502 #!/usr/bin/python # Author: Marcin Szamotulski # This file is a part of Automatic TeX Plugin for Vim. import sys, errno, os.path, shutil, subprocess, psutil, re, tempfile, optparse, glob import traceback, atexit from os import chdir, mkdir, putenv, devnull from optparse import OptionParser from collections import deque # readlink is not available on Windows. readlink=True try: from os import readlink except ImportError: readlink=False #################################### # # Parse Options: # #################################### usage = "usage: %prog [options]" parser = OptionParser(usage=usage) parser.add_option("--command", dest="command", default="pdflatex" ) parser.add_option("--bibcommand", dest="bibcommand", default="bibtex" ) parser.add_option("--progname", dest="progname", default="gvim" ) parser.add_option("--aucommand", dest="aucommand", default=False, action="store_true" ) parser.add_option("--tex-options", dest="tex_options", default="-synctex=1,-interaction=nonstopmode") parser.add_option("--verbose", dest="verbose", default="silent" ) parser.add_option("--file", dest="mainfile", ) parser.add_option("--output-format", dest="output_format", default="pdf" ) parser.add_option("--runs", dest="runs", default=1, type="int" ) parser.add_option("--servername", dest="servername", ) parser.add_option("--start", dest="start", default=0, type="int" ) parser.add_option("--viewer", dest="viewer", default="xpdf" ) parser.add_option("--xpdf-server", dest="xpdf_server", ) parser.add_option("--viewer-options", dest="viewer_opt", default="" ) parser.add_option("--keep", dest="keep", default="aux,toc,bbl,ind,pdfsync,synctex.gz") parser.add_option("--env", dest="env", default="default" ) parser.add_option("--logdir", dest="logdir") # Boolean switches: parser.add_option("--reload-viewer", action="store_true", default=False, dest="reload_viewer") parser.add_option("--bibtex", action="store_true", default=False, dest="bibtex" ) parser.add_option("--reload-on-error", action="store_true", default=False, dest="reload_on_error" ) parser.add_option("--bang", action="store_false", default=False, dest="bang" ) parser.add_option("--gui-running", action="store_true", default=False, dest="gui_running" ) parser.add_option("--autex_wait", action="store_true", default=False, dest="autex_wait" ) parser.add_option("--no-progress-bar", action="store_false", default=True, dest="progress_bar" ) parser.add_option("--bibliographies", default="", dest="bibliographies" ) (options, args) = parser.parse_args() # Debug file should be changed for sth platform independent # There should be a switch to get debug info. def nonempty(string): if str(string) == '': return False else: return True logdir = options.logdir script_logfile = os.path.join(logdir, 'compile.log') debug_file = open(script_logfile, 'w') # Cleanup on exit: def cleanup(debug_file): debug_file.close() shutil.rmtree(tmpdir) atexit.register(cleanup, debug_file) command = options.command bibcommand = options.bibcommand progname = options.progname aucommand_bool = options.aucommand if aucommand_bool: aucommand="AU" else: aucommand="COM" command_opt = list(filter(nonempty,re.split('\s*,\s*', options.tex_options))) mainfile_fp = options.mainfile output_format = options.output_format if output_format == "pdf": extension = ".pdf" else: extension = ".dvi" runs = options.runs servername = options.servername start = options.start viewer = options.viewer autex_wait = options.autex_wait XpdfServer = options.xpdf_server viewer_rawopt = re.split('\s*;\s*', options.viewer_opt) viewer_it = list(filter(nonempty,viewer_rawopt)) viewer_opt =[] for opt in viewer_it: viewer_opt.append(opt) viewer_rawopt = viewer_opt if viewer == "xpdf" and XpdfServer != None: viewer_opt.extend(["-remote", XpdfServer]) verbose = options.verbose keep = options.keep.split(',') keep = list(filter(nonempty, keep)) def keep_filter_aux(string): if string == 'aux': return False else: return True def keep_filter_log(string): if string == 'log': return False else: return True def mysplit(string): return re.split('\s*=\s*', string) env = list(map(mysplit, list(filter(nonempty, re.split('\s*;\s*',options.env))))) # Boolean options reload_viewer = options.reload_viewer bibtex = options.bibtex bibliographies = options.bibliographies.split(",") bibliographies = list(filter(nonempty, bibliographies)) bang = options.bang reload_on_error = options.reload_on_error gui_running = options.gui_running progress_bar = options.progress_bar debug_file.write("COMMAND "+command+"\n") debug_file.write("BIBCOMMAND "+bibcommand+"\n") debug_file.write("AUCOMMAND "+aucommand+"\n") debug_file.write("PROGNAME "+progname+"\n") debug_file.write("COMMAND_OPT "+str(command_opt)+"\n") debug_file.write("MAINFILE_FP "+str(mainfile_fp)+"\n") debug_file.write("OUTPUT FORMAT "+str(output_format)+"\n") debug_file.write("EXT "+extension+"\n") debug_file.write("RUNS "+str(runs)+"\n") debug_file.write("VIM_SERVERNAME "+str(servername)+"\n") debug_file.write("START "+str(start)+"\n") debug_file.write("VIEWER "+str(viewer)+"\n") debug_file.write("XPDF_SERVER "+str(XpdfServer)+"\n") debug_file.write("VIEWER_OPT "+str(viewer_opt)+"\n") debug_file.write("DEBUG MODE (verbose) "+str(verbose)+"\n") debug_file.write("KEEP "+str(keep)+"\n") debug_file.write("BIBLIOGRAPHIES "+str(bibliographies)+"\n") debug_file.write("ENV OPTION "+str(options.env)+"\n") debug_file.write("ENV "+str(env)+"\n") debug_file.write("*BIBTEX "+str(bibtex)+"\n") debug_file.write("*BANG "+str(bang)+"\n") debug_file.write("*RELOAD_VIEWER "+str(reload_viewer)+"\n") debug_file.write("*RELOAD_ON_ERROR "+str(reload_on_error)+"\n") debug_file.write("*GUI_RUNNING "+str(gui_running)+"\n") debug_file.write("*PROGRESS_BAR "+str(progress_bar)+"\n") #################################### # # Functions: # #################################### def decode_list(byte): return byte.decode() def latex_progress_bar(cmd): # Run latex and send data for progress bar, child = subprocess.Popen(cmd, stdout=subprocess.PIPE) pid = child.pid vim_remote_expr(servername, "atplib#LatexPID("+str(pid)+")") debug_file.write("latex pid "+str(pid)+"\n") stack = deque([]) while True: try: out = child.stdout.read(1).decode() except UnicodeDecodeError: debug_file.write("UNICODE DECODE ERROR:\n") debug_file.write(child.stdout.read(1)) debug_file.write("\n") out = "" if out == '' and child.poll() != None: break if out != '': stack.append(out) if len(stack)>10: stack.popleft() match = re.match('\[(\n?\d(\n|\d)*)({|\])',str(''.join(stack))) if match: vim_remote_expr(servername, "atplib#ProgressBar("+match.group(1)[match.start():match.end()]+","+str(pid)+")") child.wait() vim_remote_expr(servername, "atplib#ProgressBar('end',"+str(pid)+")") vim_remote_expr(servername, "atplib#PIDsRunning(\"b:atp_LatexPIDs\")") return child def xpdf_server_file_dict(): # Make dictionary of the type { xpdf_servername : [ file, xpdf_pid ] }, # to test if the server host file use: # basename(xpdf_server_file_dict().get(server, ['_no_file_'])[0]) == basename(file) # this dictionary always contains the full path (Linux). # TODO: this is not working as I want to: # when the xpdf was opened first without a file it is not visible in the command line # I can use 'xpdf -remote -exec "run('echo %f')"' # where get_filename is a simple program which returns the filename. # Then if the file matches I can just reload, if not I can use: # xpdf -remote -exec "openFile(file)" ps_list=psutil.get_pid_list() server_file_dict={} for pr in ps_list: try: name=psutil.Process(pr).name cmdline=psutil.Process(pr).cmdline if name == 'xpdf': try: ind=cmdline.index('-remote') except: ind=0 if ind != 0 and len(cmdline) >= 1: server_file_dict[cmdline[ind+1]]=[cmdline[len(cmdline)-1], pr] except psutil.NoSuchProcess: pass return server_file_dict def vim_remote_expr(servername, expr): # Send to vim server, # expr must be well quoted: # vim_remote_expr('GVIM', "atplib#TexReturnCode()") cmd=[progname, '--servername', servername, '--remote-expr', expr] devnull=open(os.devnull, "w+") subprocess.Popen(cmd, stdout=devnull, stderr=debug_file).wait() devnull.close() #################################### # # Arguments: # #################################### # If mainfile_fp is not a full path make it. glob=glob.glob(os.path.join(os.getcwd(),mainfile_fp)) if len(glob) != 0: mainfile_fp = glob[0] mainfile = os.path.basename(mainfile_fp) mainfile_dir = os.path.dirname(mainfile_fp) if mainfile_dir == "": mainfile_fp = os.path.join(os.getcwd(), mainfile) mainfile = os.path.basename(mainfile_fp) mainfile_dir= os.path.dirname(mainfile_fp) if os.path.islink(mainfile_fp): if readlink: mainfile_fp = os.readlink(mainfile_fp) # The above line works if the symlink was created with full path. mainfile = os.path.basename(mainfile_fp) mainfile_dir= os.path.dirname(mainfile_fp) mainfile_dir = os.path.normcase(mainfile_dir) [basename, ext] = os.path.splitext(mainfile) output_fp = os.path.splitext(mainfile_fp)[0]+extension try: # Send pid to ATP: vim_remote_expr(servername, "atplib#PythonPID("+str(os.getpid())+")") #################################### # # Make temporary directory, # Copy files and Set Environment: # #################################### cwd = os.getcwd() if not os.path.exists(os.path.join(mainfile_dir,".tmp")): # This is the main tmp dir (./.tmp) # it will not be deleted by this script # as another instance might be using it. # it is removed by Vim on exit. os.mkdir(os.path.join(mainfile_dir,".tmp")) tmpdir = tempfile.mkdtemp(dir=os.path.join(mainfile_dir,".tmp"),prefix="") debug_file.write("TMPDIR: "+tmpdir+"\n") tmpaux = os.path.join(tmpdir,basename+".aux") command_opt.append('-output-directory='+tmpdir) latex_cmd = [command]+command_opt+[mainfile_fp] debug_file.write("COMMAND "+str(latex_cmd)+"\n") debug_file.write("COMMAND "+" ".join(latex_cmd)+"\n") # Copy important files to output directory: # /except the log file/ os.chdir(mainfile_dir) for ext in filter(keep_filter_log,keep): file_cp=basename+"."+ext if os.path.exists(file_cp): shutil.copy(file_cp, tmpdir) tempdir_list = os.listdir(tmpdir) debug_file.write("ls tmpdir "+str(tempdir_list)+"\n") # Set environment for var in env: debug_file.write("ENV "+var[0]+"="+var[1]+"\n") os.putenv(var[0], var[1]) # Link local bibliographies: for bib in bibliographies: if os.path.exists(os.path.join(mainfile_dir,os.path.basename(bib))): os.symlink(os.path.join(mainfile_dir,os.path.basename(bib)),os.path.join(tmpdir,os.path.basename(bib))) #################################### # # Compile: # #################################### # Start Xpdf (this can be done before compelation, because we can load file # into afterwards) in this way Xpdf starts faster (it is already running when # file compiles). # TODO: this might cause problems when the tex file is very simple and short. # Can we test if xpdf started properly? okular doesn't behave nicely even with # --unique switch. # Latex might not run this might happedn with bibtex (?) latex_returncode=0 if bibtex and os.path.exists(tmpaux): if bibcommand == 'biber': bibfname = basename else: bibfname = basename+".aux" debug_file.write("\nBIBTEX1"+str([bibcommand, bibfname])+"\n") os.chdir(tmpdir) bibtex_popen=subprocess.Popen([bibcommand, bibfname], stdout=subprocess.PIPE) vim_remote_expr(servername, "atplib#BibtexPID('"+str(bibtex_popen.pid)+"')") vim_remote_expr(servername, "atplib#redrawstatus()") bibtex_popen.wait() vim_remote_expr(servername, "atplib#PIDsRunning(\"b:atp_BibtexPIDs\")") os.chdir(mainfile_dir) bibtex_returncode=bibtex_popen.returncode bibtex_output=re.sub('"', '\\"', bibtex_popen.stdout.read()) debug_file.write("BIBTEX RET CODE "+str(bibtex_returncode)+"\nBIBTEX OUTPUT\n"+bibtex_output+"\n") if verbose != 'verbose': vim_remote_expr(servername, "atplib#BibtexReturnCode('"+str(bibtex_returncode)+"',\""+str(bibtex_output)+"\")") else: print(bibtex_output) # We need run latex at least 2 times bibtex=False runs=max([runs, 2]) # If bibtex contained errros we stop: # if not bibtex_returncode: # runs=max([runs, 2]) # else: # runs=1 elif bibtex: # we need run latex at least 3 times runs=max([runs, 3]) debug_file.write("\nRANGE="+str(range(1,int(runs+1)))+"\n") debug_file.write("RUNS="+str(runs)+"\n") for i in range(1, int(runs+1)): debug_file.write("RUN="+str(i)+"\n") debug_file.write("DIR="+str(os.getcwd())+"\n") tempdir_list = os.listdir(tmpdir) debug_file.write("ls tmpdir "+str(tempdir_list)+"\n") debug_file.write("BIBTEX="+str(bibtex)+"\n") if verbose == 'verbose' and i == runs: # compiler() contains here ( and not bibtex ) debug_file.write("VERBOSE"+"\n") latex=subprocess.Popen(latex_cmd) pid=latex.pid debug_file.write("latex pid "+str(pid)+"\n") latex.wait() latex_returncode=latex.returncode debug_file.write("latex ret code "+str(latex_returncode)+"\n") else: if progress_bar and verbose != 'verbose': latex=latex_progress_bar(latex_cmd) else: latex = subprocess.Popen(latex_cmd, stdout=subprocess.PIPE) pid = latex.pid if verbose != "verbose": vim_remote_expr(servername, "atplib#LatexPID("+str(pid)+")") debug_file.write("latex pid "+str(pid)+"\n") latex.wait() vim_remote_expr(servername, "atplib#PIDsRunning(\"b:atp_LatexPIDs\")") latex_returncode=latex.returncode debug_file.write("latex return code "+str(latex_returncode)+"\n") tempdir_list = os.listdir(tmpdir) debug_file.write("JUST AFTER LATEX ls tmpdir "+str(tempdir_list)+"\n") # Return code of compilation: if verbose != "verbose": vim_remote_expr(servername, "atplib#TexReturnCode('"+str(latex_returncode)+"')") if bibtex and i == 1: if bibcommand == 'biber': bibfname = basename else: bibfname = basename+".aux" debug_file.write("BIBTEX2 "+str([bibcommand, bibfname])+"\n") debug_file.write(os.getcwd()+"\n") tempdir_list = os.listdir(tmpdir) debug_file.write("ls tmpdir "+str(tempdir_list)+"\n") os.chdir(tmpdir) bibtex_popen=subprocess.Popen([bibcommand, bibfname], stdout=subprocess.PIPE) vim_remote_expr(servername, "atplib#BibtexPID('"+str(bibtex_popen.pid)+"')") vim_remote_expr(servername, "atplib#redrawstatus()") bibtex_popen.wait() vim_remote_expr(servername, "atplib#PIDsRunning(\"b:atp_BibtexPIDs\")") os.chdir(mainfile_dir) bibtex_returncode=bibtex_popen.returncode bibtex_output=re.sub('"', '\\"', bibtex_popen.stdout.read()) debug_file.write("BIBTEX2 RET CODE"+str(bibtex_returncode)+"\n") if verbose != 'verbose': vim_remote_expr(servername, "atplib#BibtexReturnCode('"+str(bibtex_returncode)+"',\""+str(bibtex_output)+"\")") else: print(bibtex_output) # If bibtex had errors we stop, # at this point tex file was compiled at least once. # if bibtex_returncode: # debug_file.write("BIBTEX BREAKE "+str(bibtex_returncode)+"\n") # break #################################### # # Copy Files: # #################################### # Copy files: os.chdir(tmpdir) for ext in list(filter(keep_filter_aux,keep))+[output_format]: file_cp=basename+"."+ext if os.path.exists(file_cp): debug_file.write(file_cp+' ') shutil.copy(file_cp, mainfile_dir) # Copy aux file if there were no compilation errors or if it doesn't exists in mainfile_dir. if latex_returncode == 0 or not os.path.exists(os.path.join(mainfile_dir, basename+".aux")): file_cp=basename+".aux" if os.path.exists(file_cp): shutil.copy(file_cp, mainfile_dir) os.chdir(cwd) #################################### # # Call Back Communication: # #################################### if verbose != "verbose": debug_file.write("CALL BACK "+"atplib#CallBack('"+str(verbose)+"','"+aucommand+"','"+str(options.bibtex)+"')"+"\n") vim_remote_expr(servername, "atplib#CallBack('"+str(verbose)+"','"+aucommand+"','"+str(options.bibtex)+"')") # return code of compelation is returned before (after each compilation). #################################### # # Reload/Start Viewer: # #################################### if re.search(viewer, '^\s*xpdf\e') and reload_viewer: # The condition tests if the server XpdfServer is running xpdf_server_dict=xpdf_server_file_dict() cond = xpdf_server_dict.get(XpdfServer, ['_no_file_']) != ['_no_file_'] debug_file.write("XPDF SERVER DICT="+str(xpdf_server_dict)+"\n") debug_file.write("COND="+str(cond)+":"+str(reload_on_error)+":"+str(bang)+"\n") debug_file.write("COND="+str( not reload_on_error or bang )+"\n") debug_file.write(str(xpdf_server_dict)+"\n") if start == 1: run=['xpdf'] run.extend(viewer_opt) run.append(output_fp) debug_file.write("D1: "+str(run)+"\n") subprocess.Popen(run) elif cond and ( reload_on_error or latex_returncode == 0 or bang ): run=['xpdf', '-remote', XpdfServer, '-reload'] subprocess.Popen(run, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) debug_file.write("D2: "+str(['xpdf', '-remote', XpdfServer, '-reload'])+"\n") else: if start >= 1: run=[viewer] run.extend(viewer_opt) run.append(output_fp) debug_file.write("RUN "+str(run)+"\n") subprocess.Popen(run, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if start == 2: vim_remote_expr(servername, "atplib#SyncTex()") #################################### # # Clean: # #################################### except Exception: error_str=re.sub("'", "''",re.sub('"', '\\"', traceback.format_exc())) traceback.print_exc(None, debug_file) vim_remote_expr(servername, "atplib#Echo(\"[ATP:] error in compile.py, catched python exception:\n"+error_str+"[ATP info:] this error message is recorded in compile.py.log under g:atp_TempDir\",'echo','ErrorMsg')") sys.exit(latex_returncode) ftplugin/ATP_files/makelatex.py [[[1 511 #!/usr/bin/python # Author: Marcin Szamotulski # Date: 23 IV 2011 # This file is a part of AutomaticTexPlugin plugin for Vim. # It is distributed under General Public Licence v3 or higher. # import signal, os # def handler(signum, frame): import shutil, os.path, re, optparse, subprocess, traceback, psutil import tempfile, os, atexit, sys from optparse import OptionParser from os import getcwd from signal import SIGKILL from collections import deque usage = "usage: %prog [options]" parser = OptionParser(usage=usage) parser.add_option("--texfile", dest="texfile" ) parser.add_option("--cmd", dest="cmd", default="pdflatex" ) parser.add_option("--output-format", dest="output_format", default="pdf" ) parser.add_option("--bibcmd", dest="bibcmd", default="bibtex" ) parser.add_option("--tex-options", dest="tex_options", default="" ) parser.add_option("--outdir", dest="outdir" ) parser.add_option("--tempdir", dest="tempdir" ) parser.add_option("--progname", dest="progname", default="gvim" ) parser.add_option("--servername", dest="servername" ) parser.add_option("--viewer", dest="viewer", default="xpdf" ) parser.add_option("--xpdf-server", dest="xpdf_server", ) parser.add_option("--viewer-options", dest="viewer_opt", default="", ) parser.add_option("--start", dest="start", default=0, type="int" ) parser.add_option("--keep", dest="keep", default="aux,toc,bbl,ind,pdfsync,synctex.gz") parser.add_option("--reload-viewer", dest="reload_viewer", default=False, action="store_true") parser.add_option("--reload-on-error", dest="reload_on_error", default=False, action="store_true") parser.add_option("--bibliographies", dest="bibliographies", default="", ) # This is not yet used: parser.add_option("--force", dest="force", default=False, action="store_true") parser.add_option("--env", dest="env", default="" ) (options, args) = parser.parse_args() debugfile=os.path.join(options.tempdir, "makelatex.log") debug_file=open(debugfile, "w") texfile = options.texfile basename = os.path.splitext(os.path.basename(texfile))[0] texfile_dir = os.path.dirname(texfile) logfile = basename+".log" debug_file.write("logfile="+logfile+"\n") auxfile = basename+".aux" bibfile = basename+".bbl" idxfile = basename+".idx" indfile = basename+".ind" tocfile = basename+".toc" loffile = basename+".lof" lotfile = basename+".lot" thmfile = basename+".thm" if not os.path.exists(os.path.join(texfile_dir, ".tmp")): # This is the main tmp dir (./.tmp) # it will not be deleted by this script # as another instance might be using it. # it is removed by Vim on exit. os.mkdir(os.path.join(texfile_dir,".tmp")) tmpdir = tempfile.mkdtemp(dir=os.path.join(texfile_dir,".tmp"),prefix="") # List of pids runing. pids = [] # Cleanup on exit: def cleanup(debug_file, tmpdir, pids): debug_file.close() shutil.rmtree(tmpdir) # Will this function be called when scripts get SIGKILL, if yes # then this code might be helpful: # THIS NEEDS sys MODULE AND SIGKILL from SIGNAL MODULE # for pid in pids: # try: # os.kill(pid,SIGKILL) # except OSError: # # No such process error. # pass atexit.register(cleanup, debug_file, tmpdir, pids) # FILTER: def nonempty(str): if re.match('\s*$', str): return False else: return True servername = options.servername debug_file.write("SERVERNAME="+servername+"\n") progname = options.progname debug_file.write("PROGNAME="+progname+"\n") cmd = options.cmd debug_file.write("CMD="+cmd+"\n") tex_options = options.tex_options debug_file.write("TEX_OPTIONS="+tex_options+"\n") output_format = options.output_format if output_format == "pdf": output_ext = ".pdf" else: output_ext = ".dvi" output_fp = os.path.join(texfile_dir,basename+output_ext) debug_file.write("OUTPUT_FORMAT="+output_format+"\n") bibcmd = options.bibcmd debug_file.write("BIBCMD="+bibcmd+"\n") biber=False if re.search(bibcmd, '^\s*biber'): biber=True debug_file.write("BIBER="+str(biber)+"\n") bibliographies = options.bibliographies.split(",") bibliographies = list(filter(nonempty, bibliographies)) tex_options = list(filter(nonempty,re.split('\s*,\s*',options.tex_options))) debug_file.write("TEX_OPTIONS_LIST="+str(tex_options)+"\n") outdir = options.outdir debug_file.write("OUTDIR="+outdir+"\n") force = options.force debug_file.write("FORCE="+str(force)+"\n") start = options.start viewer = options.viewer XpdfServer = options.xpdf_server reload_viewer = options.reload_viewer reload_on_error = options.reload_on_error viewer_rawopt = re.split('\s*;\s*', options.viewer_opt) viewer_it = list(filter(nonempty,viewer_rawopt)) viewer_opt =[] for opt in viewer_it: viewer_opt.append(opt) viewer_rawopt = viewer_opt if viewer == "xpdf" and XpdfServer != None: viewer_opt.extend(["-remote", XpdfServer]) keep = options.keep.split(',') keep = list(filter(nonempty, keep)) debug_file.write("KEEP="+str(keep)+"\n") def keep_filter_aux(string): if string == 'aux': return False else: return True def keep_filter_log(string): if string == 'log': return False else: return True def mysplit(string): return re.split('\s*=\s*', string) if len(options.env)>0: env = list(map(mysplit, list(filter(nonempty, re.split('\s*;\s*',options.env))))) else: env = [] # RUN NUMBER run = 0 # BOUND (do not run pdflatex more than this) # echoerr in Vim if bound is reached. bound = 6 # FUNCTIONS def vim_remote_expr(servername, expr): # Send to vim server, # expr must be well quoted: # vim_remote_expr('GVIM', "atplib#CatchStatus()") # (this is the only way it works) # print("VIM_REMOTE_EXPR "+str(expr)) cmd=[progname, '--servername', servername, '--remote-expr', expr] devnull=open(os.devnull, "w+") subprocess.Popen(cmd, stdout=devnull, stderr=subprocess.STDOUT).wait() devnull.close() def latex_progress_bar(cmd): # Run latex and send data for progress bar, debug_file.write("RUN "+str(run)+" CMD"+str(cmd)+"\n") child = subprocess.Popen(cmd, stdout=subprocess.PIPE) pid = child.pid pids.append(pid) vim_remote_expr(servername, "atplib#LatexPID("+str(pid)+")") stack = deque([]) while True: try: out = child.stdout.read(1).decode() except UnicodeDecodeError: debug_file.write("UNICODE DECODE ERROR:\n") debug_file.write(child.stdout.read(1)) debug_file.write("\n") out = "" if out == '' and child.poll() != None: break if out != '': stack.append(out) if len(stack)>10: stack.popleft() match = re.match('\[(\n?\d(\n|\d)*)({|\])',''.join(stack)) if match: vim_remote_expr(servername, "atplib#ProgressBar("+match.group(1)[match.start():match.end()]+","+str(pid)+")") child.wait() vim_remote_expr(servername, "atplib#ProgressBar('end',"+str(pid)+")") vim_remote_expr(servername, "atplib#PIDsRunning(\"b:atp_LatexPIDs\")") return child def xpdf_server_file_dict(): # Make dictionary of the type { xpdf_servername : [ file, xpdf_pid ] }, # to test if the server host file use: # basename(xpdf_server_file_dict().get(server, ['_no_file_'])[0]) == basename(file) # this dictionary always contains the full path (Linux). # TODO: this is not working as I want to: # when the xpdf was opened first without a file it is not visible in the command line # I can use 'xpdf -remote -exec "run('echo %f')"' # where get_filename is a simple program which returns the filename. # Then if the file matches I can just reload, if not I can use: # xpdf -remote -exec "openFile(file)" ps_list=psutil.get_pid_list() server_file_dict={} for pr in ps_list: try: name=psutil.Process(pr).name cmdline=psutil.Process(pr).cmdline if name == 'xpdf': try: ind=cmdline.index('-remote') except: ind=0 if ind != 0 and len(cmdline) >= 1: server_file_dict[cmdline[ind+1]]=[cmdline[len(cmdline)-1], pr] except psutil.NoSuchProcess: pass return server_file_dict def reload_xpdf(): # Reload xpdf if asked, if re.search(viewer, '^\s*xpdf\e') and reload_viewer: cond=xpdf_server_file_dict().get(XpdfServer, ['_no_file_']) != ['_no_file_'] if cond and ( reload_on_error or latex.returncode == 0 or bang ): debug_file.write("reloading Xpdf\n") run=['xpdf', '-remote', XpdfServer, '-reload'] devnull=open(os.devnull, "w+") subprocess.Popen(run, stdout=devnull, stderr=subprocess.STDOUT) devnull.close() def copy_back_output(tmpdir): os.chdir(tmpdir) if os.path.exists(file_cp): shutil.copy(basename+output_ext, texfile_dir) os.chdir(texfile_dir) def copy_back(tmpdir, latex_returncode): os.chdir(tmpdir) if not latex_returncode or not os.path.exists(os.path.join(texfile_dir, auxfile)): ext_list=list(keep) else: ext_list=list(filter(keep_filter_aux, keep)) for ext in ext_list: file_cp=basename+"."+ext if os.path.exists(file_cp): shutil.copy(file_cp, texfile_dir) os.chdir(texfile_dir) try: # Send pid to ATP: vim_remote_expr(servername, "atplib#PythonPID("+str(os.getpid())+")") cwd = getcwd() os.chdir(texfile_dir) # Note always run first time. # this ensures that the aux, ... files are uptodate. # COPY FILES TO TEMP DIR debug_file.write("TMPDIR="+tmpdir+"\n") tmplog = os.path.join(tmpdir,basename+".log") debug_file.write("TMPLOG="+tmplog+"\n") tmpaux = os.path.join(tmpdir,basename+".aux") for ext in filter(keep_filter_log,keep): file_cp=basename+"."+ext if os.path.exists(file_cp): shutil.copy(file_cp, tmpdir) tempdir_list = os.listdir(tmpdir) debug_file.write("ls tmpdir "+str(tempdir_list)+"\n") for bib in bibliographies: if os.path.exists(os.path.join(texfile_dir,os.path.basename(bib))): os.symlink(os.path.join(texfile_dir,os.path.basename(bib)),os.path.join(tmpdir,os.path.basename(bib))) # SET ENVIRONMENT for var in env: os.putenv(var[0], var[1]) # WE RUN FOR THE FIRST TIME: # Set Environment: if len(env) > 0: for var in env: os.putenv(var[0], var[1]) output_exists=os.path.exists(os.path.join(texfile_dir,basename+output_ext)) debug_file.write("OUTPUT_EXISTS="+str(output_exists)+":"+os.path.join(texfile_dir,basename+output_ext)+"\n") latex=latex_progress_bar([cmd, '-interaction=nonstopmode', '-output-directory='+tmpdir]+tex_options+[texfile]) run += 1 latex.wait() vim_remote_expr(servername, "atplib#TexReturnCode('"+str(latex.returncode)+"')") os.chdir(tmpdir) if not output_exists: copy_back_output(tmpdir) reload_xpdf() # AFTER FIRST TIME LOG FILE SHOULD EXISTS: if os.path.isfile(tmplog): need_runs = [0] log_file = open(tmplog, "r") log = log_file.read() log_file.close() # undefined references|Citations undefined|Label(s) may have changed|Writing index file #Note: this is used only in the second run: # log_list=re.findall('(u\n?n\n?d\n?e\n?f\n?i\n?n\n?e\n?d\s+r\n?e\n?f\n?e\n?r\n?e\n?n\n?c\n?e\n?s)|(C\n?i\n?t\n?a\n?t\n?i\n?o\n?n\n?s\s+u\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\(s\)\s+m\n?a\n?y\s+h\n?a\n?v\n?e\s+c\n?h\n?a\n?n\n?g\n?e\n?d)|(W\n?r\n?i\n?t\n?i\n?n\n?g\s+i\n?n\n?d\n?e\n?x\s+f\n?i\n?l\n?e)',log) log_list=re.findall('(undefined references)|(Citations undefined)|(Label\(s\) may have changed)|(Writing index file)',log) citations =False labels =False makeidx =False for el in log_list: if el[0] != '' or el[1] != '': citations =True if biber: need_runs.append(1) else: # Bibtex: need_runs.append(2) if el[2] != '': labels =True if el[3] != '': makeidx =True need_runs.append(1) debug_file.write("citations="+str(citations)+"\n") debug_file.write("labels="+str(labels)+"\n") debug_file.write("makeidx="+str(makeidx)+"\n") # Scan for openout files to know if we are makeing: toc, lot, lof, thm openout_list=re.findall("\\\\openout\d+\s*=\s*`\"?([^'\"]*)\"?'",log) toc =False lot =False lof =False thm =False loa =False for el in openout_list: if re.search('\.toc$',el): toc=True need_runs.append(1) # We need only one more run, because of the 0-run. if re.search('\.lof$',el): lof=True need_runs.append(1) if re.search('\.lot$',el): lot=True need_runs.append(1) if re.search('\.thm$',el): thm=True need_runs.append(1) if re.search('\.loa',el): loa=True need_runs.append(1) debug_file.write("A0 need_runs="+str(need_runs)+"\n") # Aux file should be readable (we always run for the first time) # auxfile_readable = os.path.isfile(auxfile) idxfile_readable = os.path.isfile(idxfile) tocfile_readable = os.path.isfile(tocfile) loffile_readable = os.path.isfile(loffile) lotfile_readable = os.path.isfile(lotfile) thmfile_readable = os.path.isfile(thmfile) aux_file=open(tmpaux, "r") aux=aux_file.read() aux_file.close() bibtex=re.search('\\\\bibdata\s*{', aux) # This can be used to make it faster and use the old bbl file. # For this I have add a switch (bang). # bibtex=re.search('No file '+basename+'\.bbl\.', log) if not bibtex: # Then search for biblatex package. Alternatively, I can search for biblatex messages in log file. for line in open(texfile): if re.match('[^%]*\\\\usepackage\s*(\[[^]]*\])?\s*{(\w\|,)*biblatex',line): bibtex=True break elif re.search('\\\\begin\s*{\s*document\s*}',line): break debug_file.write("BIBTEX="+str(bibtex)+"\n") # I have to take the second condtion (this is the first one): condition = citations or labels or makeidx or run <= need_runs debug_file.write(str(run)+"condition="+str(condition)+"\n") # HERE IS THE MAIN LOOP: # I guess some of the code done above have to be put inside the loop. # Maybe it would be nice to make functions from some parts of the code. while condition: if run == 1: # BIBTEX if bibtex: bibtex=False os.chdir(tmpdir) if re.search(bibcmd, '^\s*biber'): auxfile = basename bibtex=subprocess.Popen([bibcmd, auxfile], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) vim_remote_expr(servername, "atplib#BibtexPID('"+str(bibtex.pid)+"')") vim_remote_expr(servername, "atplib#redrawstatus()") pids.append(bibtex.pid) bibtex.wait() vim_remote_expr(servername, "atplib#PIDsRunning(\"b:atp_BibtexPIDs\")") bibtex_output=re.sub('"', '\\"', bibtex.stdout.read().decode()) vim_remote_expr(servername, "atplib#BibtexReturnCode('"+str(bibtex.returncode)+"',\""+str(bibtex_output)+"\")") os.chdir(texfile_dir) # MAKEINDEX if makeidx: makeidx=False os.chdir(tmpdir) index=subprocess.Popen(['makeindex', idxfile], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) vim_remote_expr(servername, "atplib#MakeindexPID('"+str(index.pid)+"')") vim_remote_expr(servername, "atplib#redrawstatus()") pids.append(index.pid) index.wait() vim_remote_expr(servername, "atplib#PIDsRunning(\"b:atp_MakeindexPIDs\")") index_returncode=index.returncode os.chdir(texfile_dir) # LATEX os.chdir(texfile_dir) latex=latex_progress_bar([cmd, '-interaction=nonstopmode', '-output-directory='+tmpdir]+tex_options+[texfile]) run += 1 latex.wait() vim_remote_expr(servername, "atplib#CatchStatus('"+str(latex.returncode)+"')") reload_xpdf() copy_back_output(tmpdir) #CONDITION log_file=open(tmplog, "r") log=log_file.read() log_file.close() # Citations undefined|Label(s) may have changed # log_list=re.findall('(C\n?i\n?t\n?a\n?t\n?i\n?o\n?n\n?s\s+u\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\(s\)\s+m\n?a\n?y\s+h\n?a\n?v\n?e\s+c\n?h\n?a\n?n\n?g\n?e\n?d)',log) log_list=re.findall('(undefined references)|(Citations undefined)|(Label\(s\) may have changed)',log) citations =False labels =False for el in log_list: if el[0] != '' or el[1] != '': citations =True if el[2] != '': labels =True debug_file.write(str(run)+"citations="+str(citations)+"\n") debug_file.write(str(run)+"labels="+str(labels)+"\n") debug_file.write(str(run)+"makeidx="+str(makeidx)+"\n") debug_file.write(str(run)+"need_runs="+str(need_runs)+"\n") condition = ( (citations and run <= max(need_runs)) or labels or makeidx or run <= max(need_runs) ) and run <= bound debug_file.write(str(run)+"condition="+str(condition)+"\n") # Start viewer: (reloading xpdf is done after each compelation) if re.search(viewer, '^\s*xpdf\e') and reload_viewer: # The condition tests if the server XpdfServer is running xpdf_server_dict=xpdf_server_file_dict() cond = xpdf_server_dict.get(XpdfServer, ['_no_file_']) != ['_no_file_'] if start == 1: debug_file.write("Starting Xpdf\n") run=['xpdf'] run.extend(viewer_opt) run.append(output_fp) subprocess.Popen(run) else: if start >= 1: debug_file.write("Starting "+str(viewer)) run=[viewer] run.extend(viewer_opt) run.append(output_fp) devnull=open(os.devnull, "w+") subprocess.Popen(run, stdout=devnull, stderr=subprocess.STDOUT) devnull.close() if start == 2: debug_file.write("SyncTex with "+str(viewer)) vim_remote_expr(servername, "atplib#SyncTex()") copy_back(tmpdir, latex.returncode) # else: # THERE IS NO LOG FILE AFTER FIRST TIME: exit with error. except Exception: error_str=re.sub("'", "''",re.sub('"', '\\"', traceback.format_exc())) traceback.print_exc(None, debug_file) vim_remote_expr(servername, "atplib#Echo(\"[ATP:] error in makelatex.py, catched python exception:\n"+error_str+"[ATP info:] this error message is recorded in makelatex.log under g:atp_TempDir\",'echo','ErrorMsg')") debug_file.write("PIDS="+str(pids)) vim_remote_expr(servername, "atplib#Echo('[ATP:] MakeLatex finished.', 'echomsg', 'Normal')") sys.exit(latex.returncode) ftplugin/ATP_files/url_query.py [[[1 21 #!/usr/bin/python import sys, tempfile if sys.version_info < (3, 0): # Python 2.7 code: import sys, urllib2, tempfile url = sys.argv[1] tmpf = sys.argv[2] f = open(tmpf, "w") data = urllib2.urlopen(url) f.write(data.read()) f.close() else: # Python3 code: import urllib.request, urllib.error, urllib.parse url = sys.argv[1] tmpf = sys.argv[2] data = urllib.request.urlretrieve(url,tmpf) ftplugin/ATP_files/dictionaries/dictionary [[[1 937 Alph Arrowvert Bbbk Big Bigg Biggl Biggm Biggr Bigl Bigm Bigr Box COLON CheckCommand DeclareFixedFont DeclareFixedFont DeclareMathAccent DeclareMathDelimiter DeclareMathOperator DeclareMathRadical DeclareMathSymbol DeclareMathVersion DeclareRobustCommand DeclareSymbolFontAlphabet DeclareTextFontCommand Diamond Downarrow HUGE Huge Im Join LARGE LaTeX LaTeXe Large Leftarrow Leftrightarrow Longleftarrow Longrightarrow NeedsTeXFormat PLSlash PLdateending Re Rightarrow Roman SS SetMathAlphabet TeX Uparrow Vdash a4paper a5paper abbrv abovedisplayshortskip abovedisplayskip abstract abstract abstractname acute addcontentsline address addtime addtocontents addtocounter addtolength addvspace aleph align align* alph amalg amsmath amsthm and appendix appendixname approx arabic array arraycolsep arrayrulewidth arraystretch arrowvert article asymp author b5paper backmatter backslash bar bar baselineskip baselinestretch batchmode begin belowdisplayshortskip belowdisplayskip bezier bf bfdefault bfseries bibindent bibitem bibliography bibliographystyle bibname big bigcap bigcirc bigcup bigg biggl biggm biggr Biggr bigl Bigl bigm Bigm bigodot bigoplus bigotimes bigr Bigr bigskip bigskipamount bigsum bigtriangledown bigtriangleup bigvee bigwedge binom blacksquare blg bmatrix Bmatrix boldmath boldsymbol book booklet bot botfigrule bottmofraction bottomnumber bowtie boxedminipage bp bracevert breve bullet calc calc cap capt-of caption caption2 capt-of cases cc ccaption ccname cdot cdots cdotscenter centering cercle cfrac changebar chapter chapterbib chaptername check circ circledS cite cleardoublepage clearpage cline clock closing clubsuit cm COLON columnsep columnseprule columnwidth complement conference cong contentsline contentsname coprod copyright cup dag dagger dashbox dashv date dbinom dblfigure dblfloatpage dblfloatsep dbltextfloatsep dbltopfraction dbltopnumber dcolumn dd ddag ddager ddot ddots depth description dfrac diagdown diagup diamondsuit displaylimits displaymath displaystyle div document documentclass dot dotfill dots doublerulesep downarrow downbracefill downdownarrows draft dropping dywiz eject ell em emph empty emptyset encl enclname end endfloat enlagrethispage enlargethispage enskip enspace ensuremath enumerate enumi enumii enumiii enumiv eqnarray eqref equation equation* equiv errorstopmode eth eucal eufrak evensidemargin everyship ex executivepaper exhyphenpenalty exists expdlist extracolsep extramark fancybox fancyhdr fbox fboxrule fboxsep figure figurename file filecontents final flafter flat fleqn floatflt floatpagefraction floatsep flushbottom flushleft flushright fn2end fnpara fnsymbol fontenc fontencoding fontfamiliy fontseries fontshape fontsize footheight footmisc footnote footnotemark footnoterule footnotesep footnotesize footnotetetext footnotetext footnpag footskip forall frac frame framebox frenchspacing frontmatter frown frown ftnright fussy gather genfrac geometry geq geqslant gets gg glossary glossaryentry graphicx graphpaper grave gtrless gtrsim hat hbar hbox headheight headheihgt headings headsep heartsuit height helvet hfill hhline hline hoffset hookleftarrow hookrightarrow hrulefill hslash hspace huge hyperlink hyperref hyphenation iff ifthen imath in include includegraphics includeonly indent indentfirst index indexentry indexname indexspace infty input inputenc int intertext intextsep invisible it itdefault item itemindent itemize itemsep itshape jmath jot kill label labelenumi labelenumii labelenumiii labelenumiv labelitemi labelitemii labelitemiii labelitemiv labelsep labelwidth land landscape langle large latexsym layout lbrack lceil ldots leadsto left leftarrow leftarrowfill leftarrowtail lefteqn leftharpoondown leftharpoonup leftleftarrows leftmargin leftmargini leftmarginii leftmarginiii leftmarginiv leftmarginv leftmarginvi leftmark leftrighrarrows leftrightarrow legalpaper leq leqno leqslant lesssim letter letterpaper letterspace lfloor lgroup lhd lhead limits line linebreak linespread linethickness linewidth list listfigurename listfiles listoffigures listoftables listparindent ll lmoustache lnot location longleftarrow longmapsto longrightarrow longtable lq lrbox lscape magstep mainmatter makeatletter makeatother makebox makeglossary makeidx makeindex makelabel makelabels maketitle manyfoot mapsto marginpar marginparpush marginparsep marginparwidth markboth markleft markright math mathbb mathbf mathbin mathcal mathclose mathfrak mathindent mathit mathnormal mathop mathopen mathord mathpunct mathrel mathring mathrm mathscr mathsf mathstrut mathtt mathversion mbox mddefault mdseries medmuskip medskip medskipamount mho mid minipage minitoc minus mkern mm models moreverbatim mpfootnote mu multicol multicolumn multilanguage multiput multirow myheadings nabla name natural nearrow neq newcommand newcounter newenvironment newfont newlength newline newpage newsavebox newtheorem nexists nocite nofiles noindent nointerlineskip nolimits nolinebreak nomathsymbols nonfrenchspacing nonumber nopagebreak normal normalfont normalsize not notag note notin notitlepage nouppercase nu num numberline numline numprint nwarrow oddsidemargin odot oint oldstyle ominus onecolumn oneside onlynotes onlyslides openany openbib opening openright operatorname oplus oslash otimes oval overbrace overlay overleftarrow overline overrightarrow owns page pagebreak pagenumbering pageref pagestyle paperheight paperwidth par paragraph parbox parbox parindent parsep parskip part partial partname partopsep pauza pc perp phantom phi pi picture plain plmath plus pmb pmod polski polski poptabs pounds ppauza prec precapprox preccurlyeq preceq prefixing prime printindex prod propto protect providecommand ps pt puonds pushtabs put qbezier qbeziermax qquad quad quotation quote ragged2e raggedbottom raggedleft raggedright raisebox rangle ratio rbrack rceil real ref refname refstepcounter relsize renewcommand renewenvironemt renewenvironment report reversemarginpar rfloor rgroup rhd rhead right rightarrow rightarrowfill rightarrowtail rightharpoondown rightharpoonup rightleftarrows rightleftharpoons rightmargin rightmark rightrightarrows rm rmdefault rmfamily rmoustache roman rotate rotating rq rule samepage savebox sb sbox sc scdefault scriptscriptstyle scriptsize scriptstyle scrollmode scshape searrow secnumdepth section sectionmark see seename selectfont selectlanguage setcounter setlength setminus settime settodepth settoheight settowidth sf sfdefault sffamily shadethm shadow shapepar sharp shortstack show showlabels sidecap signature sim simeq sin sl sldefault slide slides sloppy sloppybar slshape small smallskip smallskipamount smile smile soul sp space spadesuit sqcap sqcup sqrt sqsubset sqsubseteq sqsupset sqsupseteq square ss stackrel star startbreaks stepcounter stop stopbreaks stretch strut subfigure subfigure subitem subparagraph subsection subset subseteq subsubitem subsubsection succ succapprox succcurlyeq succeq sum supressfloats supset supsetneq swarrow symbol symbol tabbing tabcolsep table tablename tableofcontents tabular tabularx tag tan tbinom telephone text textbf textbullet textcircled textcolor textcompwordmark textemdash textendash textexclamdown textfloatsep textfraction textheight textit textmd textnormal textperiodcenter textquestiondown textquotedblleft textquotedblright textquoteleft textquoteright textregistered textrm textsc textsf textsl textstyle textsuperscript texttt textup textvisiblespace textwidth tfrac thanks the thebibliography theequation theindex theorem thepage thesection theta thickapprox thicklines thickmuskip thinlines thispagestyle threeparttable tilde time times tiny title titlepage to tocdepth today top top topfigrule topfraction topmargin topmargin topmargin topsep topskip topskip totalheight totalnumber triangle triangledown trianglelefteq trianglerighteq trivlist tt ttdefault ttfamily twocolumn twocolumn twoheadleftarrow twoheadrightarrow twoside typein typein typeout typeout ulem ulem unboldmath underbrace underleftarrow underline underrightarrow unlhd unrhd unsort unsrt uparrow upbracefill updefault uplus upshape upshape upuparrows usebox usebox usecounter usefont usepackage usetikzlibrary vDash value varnothing vartriangleleft vartriangleright vbox vdash vdots vec vector verb verb verbatim verse vert vfil vfill visible vline vmargin voffset vskip vspace wedge widehat widetilde width wp wrapfig xleftarrow xrightarrow ftplugin/ATP_files/dictionaries/ams_dictionary [[[1 161 Bmatrix DeclareMatchOperator Pr align alignat allowdisplaybreaks arccos arcsin arg bmatrix bmod boxed cfrac cos cosh cot coth csc dbinom deg det dfrac dim displaybreak equation exp flalign gather gcd gneq hdotsfor hom idotsint iiiint iiint iint inf injlim intertext ker lVert leftroot lg lim liminf limsup lneq lneqq log ltimes lvert mathbb mathfrak mathscr max medspace min mod mspace multiligngap multline nLeftarrow nLeftrightarrow nRightarrow nconq negmedspace negthickspace negthinspace ngeq ngeqq ngeqq ngeqslant ngtr nleftarrow nleftrightarrow nleq nleqq nleqslant nless notag notag nprec npreceq nrightarrow nsim nsubseteq nsubseteqq nsucc nsucceq nsucceqq nsupseteq nsupseteqq ntriangleleft ntrianglelefteq ntriangleright ntrianglerighteq numberwithin nvDash nvdash overset pmatrix pmod pod precnapprox precneq precneqq projlim rVert raistag rtimes rvert sec shoveleft shoveright sideset sideset sin sinh smallmatrix smash sphat split sptilde subeqations subsetneq subsetneqq substack substack succneq succneqq sup supsetneq supsetneqq tag tag tan tanh tbinom tfrac thickspace thinspace underset uproot varDelta varGamma varLambda varOmega varPhi varPi varPsi varSigma varTheta varUpsilon varXi varinjlim varliminf varlimsup varprojlim varsubsetneq varsupsetneq vmatrix ftplugin/ATP_files/dictionaries/greek [[[1 38 alpha beta chi delta epsilon varepsilon phi psi gamma eta kappa lambda mu nu pi theta rho sigma tau upsilon varsigma vartheta omega xi zeta Delta Psi Phi Gamma Lambda Mu Nu Pi Theta Sigma Tau Upsilon Omega ftplugin/ATP_files/dictionaries/SIunits [[[1 289 addprefix addunit ampere amperemetresecond amperepermetre amperepermetrenp amperepersquaremetre amperepersquaremetrenp angstrom arad arcminute arcsecond are atomicmass atto attod barn bbar becquerel becquerelbase bel candela candelapersquaremetre candelapersquaremetrenp celsius Celsius celsiusbase centi centid coulomb coulombbase coulombpercubicmetre coulombpercubicmetrenp coulombperkilogram coulombperkilogramnp coulombpermol coulombpermolnp coulombpersquaremetre coulombpersquaremetrenp cubed cubic cubicmetre cubicmetreperkilogram cubicmetrepersecond curie dday deca decad deci decid degree degreecelsius deka dekad derbecquerel dercelsius dercoulomb derfarad dergray derhenry derhertz derjoule derkatal derlumen derlux dernewton derohm derpascal derradian dersiemens dersievert dersteradian dertesla dervolt derwatt derweber electronvolt exa exad farad faradbase faradpermetre faradpermetrenp femto femtod fourth gal giga gigad gram graybase graypersecond graypersecondnp hectare hecto hectod henry henrybase henrypermetre henrypermetrenp hertz hertzbase hour joule joulebase joulepercubicmetre joulepercubicmetrenp jouleperkelvin jouleperkelvinnp jouleperkilogram jouleperkilogramkelvin jouleperkilogramkelvinnp jouleperkilogramnp joulepermole joulepermolekelvin joulepermolekelvinnp joulepermolenp joulepersquaremetre joulepersquaremetrenp joulepertesla jouleperteslanp katal katalbase katalpercubicmetre katalpercubicmetrenp kelvin kilo kilod kilogram kilogrammetrepersecond kilogrammetrepersecondnp kilogrammetrepersquaresecond kilogrammetrepersquaresecondnp kilogrampercubicmetre kilogrampercubicmetrecoulomb kilogrampercubicmetrecoulombnp kilogrampercubicmetrenp kilogramperkilomole kilogramperkilomolenp kilogrampermetre kilogrampermetrenp kilogrampersecond kilogrampersecondcubicmetre kilogrampersecondcubicmetrenp kilogrampersecondnp kilogrampersquaremetre kilogrampersquaremetrenp kilogrampersquaremetresecond kilogrampersquaremetresecondnp kilogramsquaremetre kilogramsquaremetrenp kilogramsquaremetrepersecond kilogramsquaremetrepersecondnp kilowatthour liter litre lumen lumenbase lux luxbase mega megad meter metre metrepersecond metrepersecondnp metrepersquaresecond metrepersquaresecondnp micro microd milli millid minute mole molepercubicmetre molepercubicmetrenp nano nanod neper newton newtonbase newtonmetre newtonpercubicmetre newtonpercubicmetrenp newtonperkilogram newtonperkilogramnp newtonpermetre newtonpermetrenp newtonpersquaremetre newtonpersquaremetrenp NoAMS no@qsk ohm ohmbase ohmmetre one paminute pascal pascalbase pascalsecond pasecond per period@active persquaremetresecond persquaremetresecondnp peta petad pico picod power @qsk quantityskip rad radian radianbase radianpersecond radianpersecondnp radianpersquaresecond radianpersquaresecondnp reciprocal rem roentgen rp rpcubed rpcubic rpcubicmetreperkilogram rpcubicmetrepersecond rperminute rpersecond rpfourth rpsquare rpsquared rpsquaremetreperkilogram second siemens siemensbase sievert sievertbase square squared squaremetre squaremetrepercubicmetre squaremetrepercubicmetrenp squaremetrepercubicsecond squaremetrepercubicsecondnp squaremetreperkilogram squaremetrepernewtonsecond squaremetrepernewtonsecondnp squaremetrepersecond squaremetrepersecondnp squaremetrepersquaresecond squaremetrepersquaresecondnp steradian steradianbase tera terad tesla teslabase ton tonne unit unitskip usk volt voltbase voltpermetre voltpermetrenp watt wattbase wattpercubicmetre wattpercubicmetrenp wattperkilogram wattperkilogramnp wattpermetrekelvin wattpermetrekelvinnp wattpersquaremetre wattpersquaremetrenp wattpersquaremetresteradian wattpersquaremetresteradiannp weber weberbase yocto yoctod yotta yottad zepto zeptod zetta zettad ftplugin/bibsearch_atp.vim [[[1 136 " Vim filetype plugin file " Language: tex " Maintainer: Marcin Szamotulski " Last Change: Fri Apr 08 07:00 2011 W " 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 "[ATP:] choice yanekd to the register '" . letter . "'" | echohl None endif endfunction "}}} " vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1 ftplugin/fd_atp.vim [[[1 78 " Vim filetype plugin file " Language: tex " Maintainer: Marcin Szamotulski " Last Change: Fri Apr 08 07:00 2011 W " 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 "}}} " vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1 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 130 " 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 " Do NOT DELETE the line just below, it is used by :UpdateATP (':help atp-:UpdateATP') " Time Stamp: 10-05-11_07-40 " (but you can edit, if there is a reason for doing this. The format is dd-mm-yy_HH-MM) " Language: tex " Last Change: Sun May 01 07:00 2011 W " GetLatestVimScripts: 2945 62 :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 !exists("g:atp_reload_variables") let g:atp_reload_variables = 0 endif if &cpoptions =~ '<' echoerr "[ATP:] removing '<' from cpoptions" 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") || has("max") || has("macunix") ) " 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 " Source Project Script runtime ftplugin/ATP_files/project.vim " ATPRC file overwrites project settings " (if the user put sth in atprc file, it means that he wants this globbaly) call ReadATPRC() " 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 " Read ATPRC once again (to set mapps). call ReadATPRC() " vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1 ftplugin/bib_atp.vim [[[1 313 " 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 Apr 16 09: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') " Get data from AMS web site. let atpbib_WgetOutputFile = tempname() let URLquery_path = globpath(&rtp, 'ftplugin/ATP_files/url_query.py') let url="http://www.ams.org/mathscinet-mref?ref=".what."&dataType=bibtex" let cmd=g:atp_Python." ".URLquery_path." ".shellescape(url)." ".shellescape(atpbib_WgetOutputFile) 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 "[ATP:] 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 "[ATP:] 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 delete(atpbib_WgetOutputFile) 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("") " }}} " vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1 ftplugin/toc_atp.vim [[[1 825 " Vim filetype plugin file " Language: tex " Maintainer: Marcin Szamotulski " Last Change: Tue May 03 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 "[ATP:] 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 " YankSection, 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! YankSection(...) let register = ( a:0 >= 1 ? '"'.a:1 : '' ) " 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" " TODO: echomsg "[ATP:] can not yank last section in plain tex files :/" sleep 750m return endif " Window to go to let toc_winnr = winnr() 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 let winview = winsaveview() keepjumps call setpos('.',[0,begin_line,1,0]) normal! V if end_line != -1 && !bibliography keepjumps call setpos('.',[0, end_line, 1, 0]) elseif bibliography keepjumps 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 execute 'normal '.register.'y' call winrestview(winview) execute toc_winnr . "wincmd w" execute "let yanked_section=@".register let yanked_section_list= split(yanked_section, '\n') if yanked_section_list[0] !~ '^\s*$' call extend(yanked_section_list, [' '], 0) endif call extend(t:atp_SectionStack, [[title, type, yanked_section_list, section_nr]],0) endfunction command! -buffer -nargs=? YankSection :call YankSection() 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 "[ATP:] the stack of deleted sections is empty" return endif let buffer = s:file() " if a:after if a:type ==# "P" || line(".") == 1 let begin_line = s:getlinenr((line("."))) else 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(".") 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 "[ATP:] 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 ":YankSection [reg] Yank section under the cursor to register" echo " (by default to the unnamed register \")" echo ":DeleteSection Delete section under the cursor" echo ":PasteSection [arg] 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 " vim:fdm=marker:tw=85:ff=unix:noet:ts=8:sw=4:fdc=1 autoload/atplib.vim [[[1 5105 " 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 " Log: function! atplib#Log(file, string, ...) "{{{1 if a:0 >= 1 call delete(g:atp_TempDir."/".a:file) else exe "redir >> ".g:atp_TempDir."/".a:file silent echo a:string redir END endif endfunction "}}}1 " 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 " Table: "{{{ atplibTable, atplib#FormatListinColumns, atplib#PrintTable function! atplib#Table(list, spaces) " take a list of lists and make a list which is nicely 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 function! atplib#FormatListinColumns(list,s) " take a list and reformat it into many columns " a:s is the number of spaces between columns " for example of usage see atplib#PrintTable let max_len=max(map(copy(a:list), 'len(v:val)')) let new_list=[] let k=&l:columns/(max_len+a:s) let len=len(a:list) let column_len=len/k for i in range(0, column_len) let entry=[] for j in range(0,k) call add(entry, get(a:list, i+j*(column_len+1), "")) endfor call add(new_list,entry) endfor return new_list endfunction " Take list format it with atplib#FormatListinColumns and then with " atplib#Table (which makes columns of equal width) function! atplib#PrintTable(list, spaces) " a:list - list to print " a:spaces - nr of spaces between columns let list = atplib#FormatListinColumns(a:list, a:spaces) let nr_of_columns = max(map(copy(list), 'len(v:val)')) let spaces_list = ( nr_of_columns == 1 ? [0] : map(range(1,nr_of_columns-1), 'a:spaces') ) return atplib#Table(list, spaces_list) endfunction "}}} " QFLength "{{{ function! atplib#qflength() let lines = 1 " i.e. open with one more line than needed. for qf in getqflist() let text=substitute(qf['text'], '\_s\+', ' ', 'g') let lines+=(len(text))/&l:columns+1 endfor return lines endfunction "}}} " IMap Functions: " {{{ " These maps extend ideas from TeX_9 plugin: function! atplib#IsInMath() return atplib#CheckSyntaxGroups(g:atp_MathZones) && \ !atplib#CheckSyntaxGroups(['texMathText']) endfunction function! atplib#MakeMaps(maps, ...) let aucmd = ( a:0 >= 1 ? a:1 : '' ) " let echo = 0 for map in a:maps if map[3] != "" && ( !exists(map[5]) || {map[5]} > 0 || \ exists(map[5]) && {map[5]} == 0 && aucmd == 'InsertEnter' ) if exists(map[5]) && {map[5]} == 0 && aucmd == 'InsertEnter' exe "let ".map[5]." =1" endif " if !echo " echomsg "MAKEMAPS ".aucmd " let echo = 1 " endif exe map[0]." ".map[1]." ".map[2].map[3]." ".map[4] endif endfor endfunction function! atplib#DelMaps(maps) for map in a:maps let cmd = matchstr(map[0], '[^m]\ze\%(nore\)\=map') . "unmap" let arg = ( map[1] =~ '' ? '' : '' ) exe "silent! ".cmd." ".arg." ".map[2].map[3] " echo "silent! ".cmd." ".arg." ".map[2].map[3]."\n" endfor endfunction function! atplib#IsLeft(lchar,...) let nr = ( a:0 >= 1 ? a:1 : 0 ) " From TeX_nine plugin: let left = getline('.')[col('.')-2-nr] if left ==# a:lchar return 1 else return 0 endif endfunction " try function! atplib#ToggleMathIMaps(var, augroup) if atplib#IsInMath() call atplib#MakeMaps(a:var, a:augroup) else call atplib#DelMaps(a:var) endif endfunction " catch E127 " endtry "}}} " Compilation Call Back Communication: " with some help of D. Munger " (Communications with compiler script: both in compiler.vim and the python script.) " {{{ Compilation Call Back Communication " TexReturnCode {{{ function! atplib#TexReturnCode(returncode) let b:atp_TexReturnCode=a:returncode endfunction "}}} " BibtexReturnCode {{{ function! atplib#BibtexReturnCode(returncode,...) let b:atp_BibtexReturnCode=a:returncode let b:atp_BibtexOutput= ( a:0 >= 1 ? a:1 : "" ) 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_TexReturnCode which is equal to the value returned by tex " compiler. function! atplib#CallBack(mode,...) " If the compiler was called by autocommand. let AU = ( a:0 >= 1 ? a:1 : 'COM' ) " Was compiler called to make bibtex let BIBTEX = ( a:0 >= 2 ? a:2 : "False" ) let BIBTEX = ( BIBTEX == "True" || BIBTEX == 1 ? 1 : 0 ) if g:atp_debugCallBack call atplib#Log("CallBack.log","","init") 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 cgetfile " /this cgetfile is not working (?)/ let error = len(getqflist()) + (BIBTEX ? b:atp_BibtexReturnCode : 0) " 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 " redraw has values -0,1 " 1 do not redraw " 0 redraw " i.e. redraw at the end of function (this is done to not redraw twice in " this function) let l:clist = 0 let atp_DebugMode = t:atp_DebugMode if b:atp_TexReturnCode == 0 && ( a:mode == 'silent' || atp_DebugMode == 'silent' ) && g:atp_DebugMode_AU_change_cmdheight let &l:cmdheight=g:atp_cmdheight endif if g:atp_debugCallBack let g:debugCB = 0 let g:debugCB_mode = a:mode let g:debugCB_error = error call atplib#Log("CallBack.log","mode=".a:mode."\nerror=".error") endif let msg_list = [] let showed_message = 0 if a:mode == "silent" && !error if t:atp_QuickFixOpen if g:atp_debugCallBack let g:debugCB .= 7 endif cclose call add(msg_list, ["[ATP:] no errors, closing quick fix window.", "Normal"]) endif endif if a:mode ==? 'debug' && !error if g:atp_debugCallBack let g:debugCB .= 3 endif cclose call add(msg_list,["[ATP:] ".b:atp_TexCompiler." returned without errors [b:atp_ErrorFormat=".b:atp_ErrorFormat."]".(g:atp_DefaultDebugMode=='silent'&&atp_DebugMode!='silent'?"\ngoing out of debuging mode.": "."), "Normal", "after"]) let showed_message = 1 let t:atp_DebugMode = g:atp_DefaultDebugMode if g:atp_DefaultDebugMode == "silent" && t:atp_QuickFixOpen cclose endif let &l:cmdheight = g:atp_cmdheight endif " debug mode with errors if a:mode ==? 'debug' && error if len(getqflist()) if g:atp_debugCallBack let g:debugCB .= 4 endif let &l:cmdheight = g:atp_DebugModeCmdHeight let showed_message = 1 if b:atp_ReloadOnError || b:atp_Viewer !~ '^\s*xpdf\>' call add(msg_list, ["[ATP:] ".Compiler." returned with exit code " . b:atp_TexReturnCode . ".", (b:atp_TexReturnCode ? "ErrorMsg" : "Normal"), "before"]) else call add(msg_list, ["[ATP:] ".Compiler." returned with exit code " . b:atp_TexReturnCode . " output file not reloaded.", (b:atp_TexReturnCode ? "ErrorMsg" : "Normal"), "before"]) endif if !t:atp_QuickFixOpen let l:clist = 1 endif endif if BIBTEX && b:atp_BibtexReturnCode if g:atp_debugCallBack let g:debugCB .= 8 endif let l:clist = 1 call add(msg_list, [ "[Bib:] BibTeX returned with exit code ".b:atp_BibtexReturnCode .".", "ErrorMsg", "after"]) call add(msg_list, [ "BIBTEX_OUTPUT" , "Normal", "after"]) endif " In debug mode, go to first error. if a:mode ==# "Debug" if g:atp_debugCallBack let g:debugCB .= 6 endif cc endif endif if msg_list == [] return endif " Count length of the message: let msg_len = len(msg_list) if len(map(copy(msg_list), "v:val[0] == 'BIBTEX_OUTPUT'")) let msg_len += (BIBTEX ? len(split(b:atp_BibtexOutput, "\\n")) - 1 : - 1 ) endif let msg_len += ((len(getqflist()) <= 7 && !t:atp_QuickFixOpen) ? len(getqflist()) : 0 ) " Show messages/clist if g:atp_debugCallBack let g:msg_list = msg_list let g:clist = l:clist endif let cmdheight = &l:cmdheight let &l:cmdheight = msg_len+2 if l:clist && len(getqflist()) > 7 && !t:atp_QuickFixOpen let winnr = winnr() copen exe winnr."wincmd w" elseif (a:mode ==? "debug") && !t:atp_QuickFixOpen let l:clist = 1 endif redraw let before_msg = filter(copy(msg_list), "v:val[2] == 'before'") let after_msg = filter(copy(msg_list), "v:val[2] == 'after'") for msg in before_msg exe "echohl " . msg[1] echo msg[0] endfor let l:redraw = 1 if l:clist && len(getqflist()) <= 7 && !t:atp_QuickFixOpen if g:atp_debugCallBack let g:debugCB .= "clist" endif try clist catch E42: endtry let l:redraw = 0 endif for msg in after_msg exe "echohl " . msg[1] if msg[0] !=# "BIBTEX_OUTPUT" echo msg[0] else echo " ".substitute(b:atp_BibtexOutput, "\n", "\n ", "g") let g:debugCB .=" BIBTEX_output " endif endfor echohl Normal if len(msg_list)==0 redraw endif let &l:cmdheight = cmdheight if g:atp_debugCallBack redir END endif endfunction "}}} "{{{ LatexPID "Store LatexPIDs in a variable function! atplib#LatexPID(pid) call add(b:atp_LatexPIDs, a:pid) " call atplib#PIDsRunning("b:atp_BitexPIDs") let b:atp_LastLatexPID =a:pid endfunction "}}} "{{{ BibtexPID "Store BibtexPIDs in a variable function! atplib#BibtexPID(pid) call add(b:atp_BibtexPIDs, a:pid) " call atplib#PIDsRunning("b:atp_BibtexPIDs") endfunction "}}} "{{{ MakeindexPID "Store MakeindexPIDs in a variable function! atplib#MakeindexPID(pid) call add(b:atp_MakeindexPIDs, a:pid) let b:atp_LastMakeindexPID =a:pid endfunction "}}} "{{{ PythonPID "Store PythonPIDs in a variable function! atplib#PythonPID(pid) call add(b:atp_PythonPIDs, a:pid) " call atplib#PIDsRunning("b:atp_PythonPIDs") endfunction "}}} "{{{ MakeindexPID "Store MakeindexPIDs in a variable function! atplib#PythonPIDs(pid) call add(b:atp_PythonPIDs, a:pid) let b:atp_LastPythonPID =a:pid endfunction "}}} "{{{ PIDsRunning function! atplib#PIDsRunning(var) " a:var is a string, and might be one of 'b:atp_LatexPIDs', 'b:atp_BibtexPIDs' or " 'b:atp_MakeindexPIDs' python << EOL import psutil, re, sys, vim var = vim.eval("a:var") pids = vim.eval(var) if len(pids) > 0: ps_list=psutil.get_pid_list() rmpids=[] for lp in pids: run=False for p in ps_list: if str(lp) == str(p): run=True break if not run: rmpids.append(lp) rmpids.sort() rmpids.reverse() for pid in rmpids: vim.eval("filter("+var+", 'v:val !~ \""+str(pid)+"\"')") EOL endfunction "}}} "{{{ ProgressBar function! atplib#ProgressBar(value,pid) unlockvar b:atp_ProgressBar if a:value != 'end' let b:atp_ProgressBar[a:pid]=a:value else call remove(b:atp_ProgressBar, a:pid) endif lockvar b:atp_ProgressBar redrawstatus " redraw " echomsg a:value endfunction "}}} "{{{ redrawstatus function! atplib#redrawstatus() redrawstatus endfunction "}}} "{{{ CursorMoveI " function! atplib#CursorMoveI() " if mode() != "i" " return " endif " let cursor_pos=[ line("."), col(".")] " call feedkeys("\", "n") " call cursor(cursor_pos) " endfunction "}}} "{{{ echo function! atplib#Echo(msg,cmd,hlgroup) exe "echohl ".a:hlgroup exe a:cmd." '".a:msg."'" echohl Normal endfunction "}}} " }}} " 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 "[ATP:] 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 "[ATP:] 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', '%c')" " 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() exe "redir! > " . g:atp_TempDir."/ServerListOfFiles.log" 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 col = ( a:0 >= 1 ? a:1 : 1 ) let file = ( fnamemodify(a:file, ":e") == "tex" ? a:file : fnamemodify(a:file, ":p:r") . ".tex" ) let server_list = split(serverlist(), "\n") exe "redir! >".g:atp_TempDir."/FindAndOpen.log" echo "server list=".string(server_list) if len(server_list) == 0 return 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 echo "file:".file." line:".a:line. " col ".col." server name:".use_server." hitch-hiking server:".v:servername call system(v:progname." --servername ".use_server." --remote-wait +".a:line." ".fnameescape(file) . " &") call remote_expr(use_server, 'cursor('.a:line.','.col.')') call remote_expr(use_server, 'redraw!') " call system(v:progname." --servername ".use_server." --remote-exprt \"remote_foreground('".use_server."')\"") " This line is not working in DWM, but it might work in KDE (to be tested): " call system(v:progname." --servername ".use_server." --remote-exprt foreground\(\)") redir end return "File:".file." line:".a:line." col:".col." 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 "[ATP:] 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*}')) " for line in aux_file for line in loc_list " if line =~ '^\\newlabel' " line is of the form: " \newlabel{