From ba1305772d6dc5939fd7fbad57108aa71ee2d158 Mon Sep 17 00:00:00 2001 From: Adam Stankiewicz Date: Tue, 17 Sep 2013 01:43:28 +0200 Subject: fix: Switch latex to LaTeX-Box-Team/LaTeX-Box, fixes #6 --- ftplugin/bib_latexSuite.vim | 15 - ftplugin/latex-box/common.vim | 351 +++++++++ ftplugin/latex-box/complete.vim | 805 +++++++++++++++++++++ ftplugin/latex-box/findmain.vim | 64 ++ ftplugin/latex-box/folding.vim | 317 ++++++++ ftplugin/latex-box/latexmk.vim | 442 +++++++++++ ftplugin/latex-box/mappings.vim | 96 +++ ftplugin/latex-box/motion.vim | 518 +++++++++++++ ftplugin/latex-suite/bibtex.vim | 265 ------- ftplugin/latex-suite/brackets.vim | 144 ---- ftplugin/latex-suite/compiler.vim | 874 ---------------------- ftplugin/latex-suite/custommacros.vim | 255 ------- ftplugin/latex-suite/diacritics.vim | 124 ---- ftplugin/latex-suite/elementmacros.vim | 330 --------- ftplugin/latex-suite/envmacros.vim | 1166 ------------------------------ ftplugin/latex-suite/folding.vim | 400 ---------- ftplugin/latex-suite/main.vim | 1042 -------------------------- ftplugin/latex-suite/mathmacros-utf.vim | 729 ------------------- ftplugin/latex-suite/mathmacros.vim | 730 ------------------- ftplugin/latex-suite/multicompile.vim | 16 - ftplugin/latex-suite/packages.vim | 676 ----------------- ftplugin/latex-suite/projecttemplate.vim | 11 - ftplugin/latex-suite/smartspace.vim | 102 --- ftplugin/latex-suite/templates.vim | 148 ---- ftplugin/latex-suite/texmenuconf.vim | 130 ---- ftplugin/latex-suite/texproject.vim | 54 -- ftplugin/latex-suite/texviewer.vim | 1070 --------------------------- ftplugin/latex-suite/version.vim | 30 - ftplugin/latex-suite/wizardfuncs.vim | 376 ---------- ftplugin/latextoc.vim | 166 +++++ ftplugin/tex_LatexBox.vim | 33 + ftplugin/tex_latexSuite.vim | 13 - 32 files changed, 2792 insertions(+), 8700 deletions(-) delete mode 100644 ftplugin/bib_latexSuite.vim create mode 100644 ftplugin/latex-box/common.vim create mode 100644 ftplugin/latex-box/complete.vim create mode 100644 ftplugin/latex-box/findmain.vim create mode 100644 ftplugin/latex-box/folding.vim create mode 100644 ftplugin/latex-box/latexmk.vim create mode 100644 ftplugin/latex-box/mappings.vim create mode 100644 ftplugin/latex-box/motion.vim delete mode 100644 ftplugin/latex-suite/bibtex.vim delete mode 100644 ftplugin/latex-suite/brackets.vim delete mode 100644 ftplugin/latex-suite/compiler.vim delete mode 100644 ftplugin/latex-suite/custommacros.vim delete mode 100644 ftplugin/latex-suite/diacritics.vim delete mode 100644 ftplugin/latex-suite/elementmacros.vim delete mode 100644 ftplugin/latex-suite/envmacros.vim delete mode 100644 ftplugin/latex-suite/folding.vim delete mode 100644 ftplugin/latex-suite/main.vim delete mode 100644 ftplugin/latex-suite/mathmacros-utf.vim delete mode 100644 ftplugin/latex-suite/mathmacros.vim delete mode 100644 ftplugin/latex-suite/multicompile.vim delete mode 100644 ftplugin/latex-suite/packages.vim delete mode 100644 ftplugin/latex-suite/projecttemplate.vim delete mode 100644 ftplugin/latex-suite/smartspace.vim delete mode 100644 ftplugin/latex-suite/templates.vim delete mode 100644 ftplugin/latex-suite/texmenuconf.vim delete mode 100644 ftplugin/latex-suite/texproject.vim delete mode 100644 ftplugin/latex-suite/texviewer.vim delete mode 100644 ftplugin/latex-suite/version.vim delete mode 100644 ftplugin/latex-suite/wizardfuncs.vim create mode 100644 ftplugin/latextoc.vim create mode 100644 ftplugin/tex_LatexBox.vim delete mode 100644 ftplugin/tex_latexSuite.vim (limited to 'ftplugin') diff --git a/ftplugin/bib_latexSuite.vim b/ftplugin/bib_latexSuite.vim deleted file mode 100644 index 7a8d47d1..00000000 --- a/ftplugin/bib_latexSuite.vim +++ /dev/null @@ -1,15 +0,0 @@ -" File: bib_latexSuite.vim -" Author: Srinath Avadhanula -" License: Vim Charityware License -" Description: -" This file sources the bibtex.vim file distributed as part of latex-suite. -" That file sets up 3 maps BBB, BAS, and BBA which are easy wasy to type in -" bibliographic entries. -" - -" source main.vim because we need a few functions from it. -runtime ftplugin/latex-suite/main.vim -" Disable smart-quotes because we need to enter real quotes in bib files. -runtime ftplugin/latex-suite/bibtex.vim - -" vim:fdm=marker:ff=unix:noet:ts=4:sw=4:nowrap diff --git a/ftplugin/latex-box/common.vim b/ftplugin/latex-box/common.vim new file mode 100644 index 00000000..91026720 --- /dev/null +++ b/ftplugin/latex-box/common.vim @@ -0,0 +1,351 @@ +" LaTeX Box common functions + +" Error Format {{{ +" Note: The error formats assume we're using the -file-line-error with +" [pdf]latex. + +" Check for options +if !exists("g:LatexBox_show_warnings") + let g:LatexBox_show_warnings=1 +endif +if !exists("g:LatexBox_ignore_warnings") + let g:LatexBox_ignore_warnings = + \['Underfull', + \ 'Overfull', + \ 'specifier changed to'] +endif + +" See |errorformat-LaTeX| +setlocal efm=%E!\ LaTeX\ %trror:\ %m +setlocal efm+=%E%f:%l:\ %m + +" Show or ignore warnings +if g:LatexBox_show_warnings + for w in g:LatexBox_ignore_warnings + let warning = escape(substitute(w, '[\,]', '%\\\\&', 'g'), ' ') + exe 'setlocal efm+=%-G%.%#'. warning .'%.%#' + endfor + setlocal efm+=%+WLaTeX\ %.%#Warning:\ %.%#line\ %l%.%# + setlocal efm+=%+W%.%#\ at\ lines\ %l--%*\\d + setlocal efm+=%+WLaTeX\ %.%#Warning:\ %m + setlocal efm+=%+W%.%#%.%#Warning:\ %m +else + setlocal efm+=%-WLaTeX\ %.%#Warning:\ %.%#line\ %l%.%# + setlocal efm+=%-W%.%#\ at\ lines\ %l--%*\\d + setlocal efm+=%-WLaTeX\ %.%#Warning:\ %m + setlocal efm+=%-W%.%#%.%#Warning:\ %m +endif + +" Consider the remaining statements that starts with "!" as errors +setlocal efm+=%E!\ %m + +" Push file to file stack +setlocal efm+=%+P**%f + +" Ignore unmatched lines +setlocal efm+=%-G\\s%# +setlocal efm+=%-G%.%# +" }}} + +" Vim Windows {{{ + +" Width of vertical splits +if !exists('g:LatexBox_split_width') + let g:LatexBox_split_width = 30 +endif + +" Where vertical splits appear +if !exists('g:LatexBox_split_side') + let g:LatexBox_split_side = "leftabove" +endif + +" Resize when split? +if !exists('g:LatexBox_split_resize') + let g:LatexBox_split_resize = 0 +endif + +" Toggle help info +if !exists('g:LatexBox_toc_hidehelp') + let g:LatexBox_toc_hidehelp = 0 +endif +" }}} + +" Filename utilities {{{ +function! LatexBox_GetMainTexFile() + + " 1. check for the b:main_tex_file variable + if exists('b:main_tex_file') && filereadable(b:main_tex_file) + return b:main_tex_file + endif + + + " 2. scan the first few lines of the file for root = filename + for linenum in range(1,5) + let linecontents = getline(linenum) + if linecontents =~ 'root\s*=' + " Remove everything but the filename + let b:main_tex_file = substitute(linecontents, + \ '.*root\s*=\s*', "", "") + let b:main_tex_file = substitute(b:main_tex_file, '\s*$', "", "") + " Prepend current directory if this isn't an absolute path + if b:main_tex_file !~ '^/' + let b:main_tex_file = expand('%:p:h') . '/' . b:main_tex_file + endif + let b:main_tex_file = fnamemodify(b:main_tex_file, ":p") + if b:main_tex_file !~ '\.tex$' + let b:main_tex_file .= '.tex' + endif + return b:main_tex_file + endif + endfor + + " 3. scan current file for "\begin{document}" + if &filetype == 'tex' && search('\C\\begin\_\s*{document}', 'nw') != 0 + return expand('%:p') + endif + + " 4 borrow the Vim-Latex-Suite method of finding it + if Tex_GetMainFileName() != expand('%:p') + let b:main_tex_file = Tex_GetMainFileName() + return b:main_tex_file + endif + + " 5. 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 ' . fnameescape(expand('%:p:h')) + let l:file = '' + while !filereadable(l:file) + let l:file = input('main LaTeX file: ', '', 'file') + if l:file !~ '\.tex$' + let l:file .= '.tex' + endif + endwhile + let l:file = fnamemodify(l:file, ':p') + execute 'cd ' . fnameescape(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() + " 1. check for b:build_dir variable + if exists('b:build_dir') && isdirectory(b:build_dir) + return b:build_dir . '/' . LatexBox_GetTexBasename(0) . '.aux' + endif + + " 2. check for g:LatexBox_build_dir variable + if exists('g:LatexBox_build_dir') && isdirectory(g:LatexBox_build_dir) + return g:LatexBox_build_dir . '/' . LatexBox_GetTexBasename(0) . '.aux' + endif + + " 3. use the base name of main tex file + return LatexBox_GetTexBasename(1) . '.aux' +endfunction + +function! LatexBox_GetLogFile() + " 1. check for b:build_dir variable + if exists('b:build_dir') && isdirectory(b:build_dir) + return b:build_dir . '/' . LatexBox_GetTexBasename(0) . '.log' + endif + + " 2. check for g:LatexBox_build_dir variable + if exists('g:LatexBox_build_dir') && isdirectory(g:LatexBox_build_dir) + return g:LatexBox_build_dir . '/' . LatexBox_GetTexBasename(0) . '.log' + endif + + " 3. use the base name of main tex file + return LatexBox_GetTexBasename(1) . '.log' +endfunction + +function! LatexBox_GetOutputFile() + " 1. check for b:build_dir variable + if exists('b:build_dir') && isdirectory(b:build_dir) + return b:build_dir . '/' . LatexBox_GetTexBasename(0) + \ . '.' . g:LatexBox_output_type + endif + + " 2. check for g:LatexBox_build_dir variable + if exists('g:LatexBox_build_dir') && isdirectory(g:LatexBox_build_dir) + return g:LatexBox_build_dir . '/' . LatexBox_GetTexBasename(0) + \ . '.' . g:LatexBox_output_type + endif + + " 3. use the base name of main tex file + return LatexBox_GetTexBasename(1) . '.' . g:LatexBox_output_type +endfunction +" }}} + +" View Output {{{ + +" Default pdf viewer +if !exists('g:LatexBox_viewer') + if has('win32') + " On windows, 'running' a file will open it with the default program + let g:LatexBox_viewer = '' + else + let g:LatexBox_viewer = 'xdg-open' + endif +endif + +function! LatexBox_View() + let outfile = LatexBox_GetOutputFile() + if !filereadable(outfile) + echomsg fnamemodify(outfile, ':.') . ' is not readable' + return + endif + let cmd = g:LatexBox_viewer . ' ' . shellescape(outfile) + if has('win32') + let cmd = '!start /b' . cmd . ' >nul' + else + let cmd = '!' . cmd . ' >/dev/null &' + endif + silent execute cmd + if !has("gui_running") + redraw! + 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 diff --git a/ftplugin/latex-box/complete.vim b/ftplugin/latex-box/complete.vim new file mode 100644 index 00000000..76f909b9 --- /dev/null +++ b/ftplugin/latex-box/complete.vim @@ -0,0 +1,805 @@ +" LaTeX Box completion + +setlocal omnifunc=LatexBox_Complete + +" 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 +" }}} + +" 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\\\a*cite\a*\*\?\(\[[^\]]*\]\)*\_\s*{' +endif +if !exists('g:LatexBox_ref_pattern') + let g:LatexBox_ref_pattern = '\C\\v\?\(eq\|page\|[cC]\)\?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 + +if !exists('g:LatexBox_complete_inlineMath') + let g:LatexBox_complete_inlineMath = 0 +endif + +if !exists('g:LatexBox_eq_env_patterns') + let g:LatexBox_eq_env_patterns = 'equation\|gather\|multiline\|align\|flalign\|alignat\|eqnarray' +endif + +" }}} + +"LatexBox_kpsewhich {{{ +function! LatexBox_kpsewhich(file) + let old_dir = getcwd() + execute 'lcd ' . fnameescape(LatexBox_GetTexRoot()) + let out = system('kpsewhich "' . a:file . '"') + + " If kpsewhich has found something, it returns a non-empty string with a + " newline at the end; otherwise the string is empty + if len(out) + " Remove the trailing newline + let out = fnamemodify(out[:-2], ':p') + endif + + execute 'lcd ' . fnameescape(old_dir) + + return out +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 + elseif s:LatexBox_complete_inlineMath_or_not() + let s:completion_type = 'inlineMath' + let pos = s:eq_pos + 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) + elseif s:completion_type == 'inlineMath' + let suggestions = s:LatexBox_inlineMath_completion(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! s:FindBibData(...) + if a:0 == 0 + let file = LatexBox_GetMainTexFile() + else + let file = a:1 + endif + + if !filereadable(file) + return '' + endif + + let bibliography_cmds = [ + \ '\\bibliography', + \ '\\addbibresource', + \ '\\addglobalbib', + \ '\\addsectionbib', + \ ] + + let lines = readfile(file) + + let bibdata_list = [] + + for cmd in bibliography_cmds + let bibdata_list += map(filter(copy(lines), + \ 'v:val =~ ''\C' . cmd . '\s*{[^}]\+}'''), + \ 'matchstr(v:val, ''\C' . cmd . '\s*{\zs[^}]\+\ze}'')') + endfor + + 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'')))') + + return join(bibdata_list, ',') +endfunction + +let s:bstfile = expand(':p:h') . '/vimcomplete' + +function! LatexBox_BibSearch(regexp) + let res = [] + + " Find data from bib files + let bibdata = s:FindBibData() + if bibdata != '' + + " write temporary aux file + let tmpbase = LatexBox_GetTexRoot() . '/_LatexBox_BibComplete' + let auxfile = tmpbase . '.aux' + let bblfile = tmpbase . '.bbl' + let blgfile = tmpbase . '.blg' + + call writefile(['\citation{*}', '\bibstyle{' . s:bstfile . '}', + \ '\bibdata{' . bibdata . '}'], auxfile) + + silent execute '! cd ' shellescape(LatexBox_GetTexRoot()) . + \ ' ; bibtex -terse ' + \ . fnamemodify(auxfile, ':t') . ' >/dev/null' + + 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) + endif + + " Find data from 'thebibliography' environments + let lines = readfile(LatexBox_GetMainTexFile()) + if match(lines, '\C\\begin{thebibliography}') + for line in filter(filter(lines, 'v:val =~ ''\C\\bibitem'''), + \ 'v:val =~ a:regexp') + let match = matchlist(line, '\\bibitem{\([^}]*\)')[1] + call add(res, { + \ 'key': match, + \ 'type': '', + \ 'author': '', + \ 'year': '', + \ 'title': match, + \ }) + endfor + endif + + 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 type = m['type'] == '' ? '[-]' : '[' . m['type'] . '] ' + let auth = m['author'] == '' ? '' : m['author'][:20] . ' ' + let year = m['year'] == '' ? '' : '(' . m['year'] . ')' + let w = { 'word': m['key'], + \ 'abbr': type . auth . 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 +" }}} + +" ExtractLabels {{{ +" Generate list of \newlabel commands in current buffer. +" +" Searches the current buffer for commands of the form +" \newlabel{name}{{number}{page}.* +" and returns list of [ name, number, page ] tuples. +function! s:ExtractLabels() + call cursor(1,1) + + let matches = [] + let [lblline, lblbegin] = searchpos( '\\newlabel{', 'ecW' ) + + while [lblline, lblbegin] != [0,0] + let [nln, nameend] = searchpairpos( '{', '', '}', 'W' ) + if nln != lblline + let [lblline, lblbegin] = searchpos( '\\newlabel{', 'ecW' ) + continue + endif + let curname = strpart( getline( lblline ), lblbegin, nameend - lblbegin - 1 ) + + " Ignore cref entries (because they are duplicates) + if curname =~ "\@cref" + continue + endif + + if 0 == search( '{\w*{', 'ce', lblline ) + let [lblline, lblbegin] = searchpos( '\\newlabel{', 'ecW' ) + continue + endif + + let numberbegin = getpos('.')[2] + let [nln, numberend] = searchpairpos( '{', '', '}', 'W' ) + if nln != lblline + let [lblline, lblbegin] = searchpos( '\\newlabel{', 'ecW' ) + continue + endif + let curnumber = strpart( getline( lblline ), numberbegin, numberend - numberbegin - 1 ) + + if 0 == search( '\w*{', 'ce', lblline ) + let [lblline, lblbegin] = searchpos( '\\newlabel{', 'ecW' ) + continue + endif + + let pagebegin = getpos('.')[2] + let [nln, pageend] = searchpairpos( '{', '', '}', 'W' ) + if nln != lblline + let [lblline, lblbegin] = searchpos( '\\newlabel{', 'ecW' ) + continue + endif + let curpage = strpart( getline( lblline ), pagebegin, pageend - pagebegin - 1 ) + + let matches += [ [ curname, curnumber, curpage ] ] + + let [lblline, lblbegin] = searchpos( '\\newlabel{', 'ecW' ) + endwhile + + return matches +endfunction +"}}} + +" ExtractInputs {{{ +" Generate list of \@input commands in current buffer. +" +" Searches the current buffer for \@input{file} entries and +" returns list of all files. +function! s:ExtractInputs() + call cursor(1,1) + + let matches = [] + let [inline, inbegin] = searchpos( '\\@input{', 'ecW' ) + + while [inline, inbegin] != [0,0] + let [nln, inend] = searchpairpos( '{', '', '}', 'W' ) + if nln != inline + let [inline, inbegin] = searchpos( '\\@input{', 'ecW' ) + continue + endif + let matches += [ LatexBox_kpsewhich(strpart( getline( inline ), inbegin, inend - inbegin - 1 )) ] + + let [inline, inbegin] = searchpos( '\\@input{', 'ecW' ) + endwhile + + " Remove empty strings for nonexistant .aux files + return filter(matches, 'v:val != ""') +endfunction +"}}} + +" LabelCache {{{ +" Cache of all labels. +" +" LabelCache is a dictionary mapping filenames to tuples +" [ time, labels, inputs ] +" where +" * time is modification time of the cache entry +" * labels is a list like returned by ExtractLabels +" * inputs is a list like returned by ExtractInputs +let s:LabelCache = {} +"}}} + +" GetLabelCache {{{ +" Extract labels from LabelCache and update it. +" +" Compares modification time of each entry in the label +" cache and updates it, if necessary. During traversal of +" the LabelCache, all current labels are collected and +" returned. +function! s:GetLabelCache(file) + if !filereadable(a:file) + return [] + endif + + if !has_key(s:LabelCache , a:file) || s:LabelCache[a:file][0] != getftime(a:file) + " Open file in temporary split window for label extraction. + silent execute '1sp +let\ labels=s:ExtractLabels()|let\ inputs=s:ExtractInputs()|quit! ' . a:file + let s:LabelCache[a:file] = [ getftime(a:file), labels, inputs ] + endif + + " We need to create a copy of s:LabelCache[fid][1], otherwise all inputs' + " labels would be added to the current file's label cache upon each + " completion call, leading to duplicates/triplicates/etc. and decreased + " performance. + " Also, because we don't anything with the list besides matching copies, + " we can get away with a shallow copy for now. + let labels = copy(s:LabelCache[a:file][1]) + + for input in s:LabelCache[a:file][2] + let labels += s:GetLabelCache(input) + endfor + + return labels +endfunction +"}}} + +" Complete Labels {{{ +function! s:CompleteLabels(regex) + let labels = s:GetLabelCache(LatexBox_GetAuxFile()) + + let matches = filter( copy(labels), 'match(v:val[0], "' . a:regex . '") != -1' ) + 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 = filter( copy(labels), 'match(v:val[0], "' . base . '") != -1 && match(v:val[1], "' . number . '") != -1' ) + endif + endif + if empty(matches) + " also try to match number + let matches = filter( copy(labels), 'match(v:val[1], "' . a:regex . '") != -1' ) + endif + + let suggestions = [] + for m in matches + let entry = {'word': m[0], 'menu': printf("%7s [p. %s]", '('.m[1].')', m[2])} + 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) + endfor + + return suggestions +endfunction +" }}} + +" Complete Inline Math Or Not {{{ +" Return 1, when cursor is in a math env: +" 1, there is a single $ in the current line on the left of cursor +" 2, there is an open-eq-env on/above the current line +" (open-eq-env : \(, \[, and \begin{eq-env} ) +" Return 0, when cursor is not in a math env +function! s:LatexBox_complete_inlineMath_or_not() + + " switch of inline math completion feature + if g:LatexBox_complete_inlineMath == 0 + return 0 + endif + + " env names that can't appear in an eq env + if !exists('s:LatexBox_doc_structure_patterns') + let s:LatexBox_doc_structure_patterns = '\%(' . '\\begin\s*{document}\|' . + \ '\\\%(chapter\|section\|subsection\|subsubsection\)\*\?\s*{' . '\)' + endif + + if !exists('s:LatexBox_eq_env_open_patterns') + let s:LatexBox_eq_env_open_patterns = ['\\(','\\\['] + endif + if !exists('s:LatexBox_eq_env_close_patterns') + let s:LatexBox_eq_env_close_patterns = ['\\)','\\\]'] + endif + + let notcomment = '\%(\%(\\\@= 0 + " find the end of dollar pair + let cursor_dollar_pair = matchend(line_start_2_cnum_saved, '\$[^$]\+\$', cursor_dollar_pair) + endwhile + " find single $ after cursor_dollar_pair + let cursor_single_dollar = matchend(line_start_2_cnum_saved, '\$', cursor_dollar_pair) + + " if single $ is found + if cursor_single_dollar >= 0 + " check whether $ is in \(...\), \[...\], or \begin{eq}...\end{eq} + + " check current line, + " search for LatexBox_eq_env_close_patterns: \[ and \( + let lnum = line('.') + for i in range(0, (len(s:LatexBox_eq_env_open_patterns)-1)) + call cursor(lnum_saved, cnum_saved) + let cnum_close = searchpos(''. s:LatexBox_eq_env_close_patterns[i].'', 'cbW', lnum_saved)[1] + let cnum_open = matchend(line_start_2_cnum_saved, s:LatexBox_eq_env_open_patterns[i], cnum_close) + if cnum_open >= 0 + let s:eq_dollar_parenthesis_bracket_empty = '' + let s:eq_pos = cursor_single_dollar - 1 + return 1 + end + endfor + + " check the lines above + " search for s:LatexBox_doc_structure_patterns, and end-of-math-env + let lnum -= 1 + while lnum > 0 + let line = getline(lnum) + if line =~ notcomment . '\(' . s:LatexBox_doc_structure_patterns . + \ '\|' . '\\end\s*{\(' . g:LatexBox_eq_env_patterns . '\)\*\?}\)' + " when s:LatexBox_doc_structure_patterns or g:LatexBox_eq_env_patterns + " are found first, complete math, leave with $ at both sides + let s:eq_dollar_parenthesis_bracket_empty = '$' + let s:eq_pos = cursor_single_dollar + break + elseif line =~ notcomment . '\\begin\s*{\(' . g:LatexBox_eq_env_patterns . '\)\*\?}' + " g:LatexBox_eq_env_patterns is found, complete math, remove $ + let s:eq_dollar_parenthesis_bracket_empty = '' + let s:eq_pos = cursor_single_dollar - 1 + break + endif + let lnum -= 1 + endwhile + + return 1 + else + " no $ is found, then search for \( or \[ in current line + " 1, whether there is \( + call cursor(lnum_saved, cnum_saved) + let cnum_parenthesis_close = searchpos('\\)', 'cbW', lnum_saved)[1] + let cnum_parenthesis_open = matchend(line_start_2_cnum_saved, '\\(', cnum_parenthesis_close) + if cnum_parenthesis_open >= 0 + let s:eq_dollar_parenthesis_bracket_empty = '\)' + let s:eq_pos = cnum_parenthesis_open + return 1 + end + + " 2, whether there is \[ + call cursor(lnum_saved, cnum_saved) + let cnum_bracket_close = searchpos('\\\]', 'cbW', lnum_saved)[1] + let cnum_bracket_open = matchend(line_start_2_cnum_saved, '\\\[', cnum_bracket_close) + if cnum_bracket_open >= 0 + let s:eq_dollar_parenthesis_bracket_empty = '\]' + let s:eq_pos = cnum_bracket_open + return 1 + end + + " not inline math completion + return 0 + endif + +endfunction +" }}} + +" Complete inline euqation{{{ +function! s:LatexBox_inlineMath_completion(regex, ...) + + if a:0 == 0 + let file = LatexBox_GetMainTexFile() + else + let file = a:1 + endif + + if empty(glob(file, 1)) + return '' + endif + + if empty(s:eq_dollar_parenthesis_bracket_empty) + let inline_pattern1 = '\$\s*\(' . escape(substitute(a:regex[1:], '^\s\+', '', ""), '\.*^') . '[^$]*\)\s*\$' + let inline_pattern2 = '\\(\s*\(' . escape(substitute(a:regex[1:], '^\s\+', '', ""), '\.*^') . '.*\)\s*\\)' + else + let inline_pattern1 = '\$\s*\(' . escape(substitute(a:regex, '^\s\+', '', ""), '\.*^') . '[^$]*\)\s*\$' + let inline_pattern2 = '\\(\s*\(' . escape(substitute(a:regex, '^\s\+', '', ""), '\.*^') . '.*\)\s*\\)' + endif + + + let suggestions = [] + let line_num = 0 + for line in readfile(file) + let line_num = line_num + 1 + + let suggestions += s:LatexBox_inlineMath_mathlist(line,inline_pattern1 , line_num) + s:LatexBox_inlineMath_mathlist( line,inline_pattern2, line_num) + + " 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:LatexBox_inlineMath_completion(a:regex, included_file)) + endif + endfor + + return suggestions +endfunction +" }}} + +" Search for inline maths {{{ +" search for $ ... $ and \( ... \) in each line +function! s:LatexBox_inlineMath_mathlist(line,inline_pattern, line_num) + let col_start = 0 + let suggestions = [] + while 1 + let matches = matchlist(a:line, a:inline_pattern, col_start) + if !empty(matches) + + " show line number of inline math + let entry = {'word': matches[1], 'menu': '[' . a:line_num . ']'} + + if s:eq_dollar_parenthesis_bracket_empty != '' + let entry = copy(entry) + let entry.abbr = entry.word + let entry.word = entry.word . s:eq_dollar_parenthesis_bracket_empty + endif + call add(suggestions, entry) + + " update col_start + let col_start = matchend(a:line, a:inline_pattern, col_start) + else + break + endif + endwhile + + return suggestions +endfunction +" }}} + +" Close Current Environment {{{ +function! s:CloseCurEnv() + " first, try with \left/\right pairs + let [lnum, cnum] = searchpairpos('\C\\left\>', '', '\C\\right\>', 'bnW', 'LatexBox_InComment()') + if lnum + let line = strpart(getline(lnum), cnum - 1) + let bracket = matchstr(line, '^\\left\zs\((\|\[\|\\{\||\|\.\)\ze') + for [open, close] in [['(', ')'], ['\[', '\]'], ['\\{', '\\}'], ['|', '|'], ['\.', '|']] + let bracket = substitute(bracket, open, close, 'g') + endfor + return '\right' . bracket + endif + + " second, try with environments + let env = LatexBox_GetCurrentEnvironment() + if env == '\[' + return '\]' + elseif env == '\(' + return '\)' + elseif env != '' + return '\end{' . env . '}' + endif + return '' +endfunction +" }}} + +" Wrap Selection {{{ +function! s:WrapSelection(wrapper) + keepjumps normal! `>a} + execute 'keepjumps normal! `o\end{' . env . '}' + execute 'keepjumps normal! ` + normal! gvgq + endif + else + execute 'keepjumps normal! `>a\end{' . env . '}' + execute 'keepjumps normal! ` LatexCloseCurEnv =CloseCurEnv() +vnoremap LatexWrapSelection :call WrapSelection('')i +vnoremap LatexEnvWrapSelection :call PromptEnvWrapSelection() +vnoremap LatexEnvWrapFmtSelection :call PromptEnvWrapSelection(1) +nnoremap LatexChangeEnv :call ChangeEnvPrompt() +" }}} + +" vim:fdm=marker:ff=unix:noet:ts=4:sw=4 diff --git a/ftplugin/latex-box/findmain.vim b/ftplugin/latex-box/findmain.vim new file mode 100644 index 00000000..0b9c404f --- /dev/null +++ b/ftplugin/latex-box/findmain.vim @@ -0,0 +1,64 @@ +" Tex_GetMainFileName: gets the name of the main file being compiled. {{{ +" Description: returns the full path name of the main file. +" This function checks for the existence of a .latexmain file +" which might point to the location of a "main" latex file. +" If .latexmain exists, then return the full path name of the +" file being pointed to by it. +" +" Otherwise, return the full path name of the current buffer. +" +" You can supply an optional "modifier" argument to the +" function, which will optionally modify the file name before +" returning. +" NOTE: From version 1.6 onwards, this function always trims +" away the .latexmain part of the file name before applying the +" modifier argument. +function! Tex_GetMainFileName(...) + if a:0 > 0 + let modifier = a:1 + else + let modifier = ':p' + endif + + let s:origdir = fnameescape(getcwd()) + + let dirmodifier = '%:p:h' + let dirLast = fnameescape(expand(dirmodifier)) + exe 'cd '.dirLast + + " move up the directory tree until we find a .latexmain file. + " TODO: Should we be doing this recursion by default, or should there be a + " setting? + while glob('*.latexmain') == '' + let dirmodifier = dirmodifier.':h' + let dirNew = fnameescape(expand(dirmodifier)) + " break from the loop if we cannot go up any further. + if dirNew == dirLast + break + endif + let dirLast = dirNew + exe 'cd '.dirLast + endwhile + + let lheadfile = glob('*.latexmain') + if lheadfile != '' + " Remove the trailing .latexmain part of the filename... We never want + " that. + let lheadfile = fnamemodify(substitute(lheadfile, '\.latexmain$', '', ''), modifier) + else + " If we cannot find any main file, just modify the filename of the + " current buffer. + let lheadfile = expand('%'.modifier) + endif + + if lheadfile !~ '\.tex$' + let lheadfile .= '.tex' + endif + exe 'cd '.s:origdir + + " NOTE: The caller of this function needs to escape the file name with + " fnameescape() . The reason its not done here is that escaping is not + " safe if this file is to be used as part of an external command on + " certain platforms. + return lheadfile +endfunction diff --git a/ftplugin/latex-box/folding.vim b/ftplugin/latex-box/folding.vim new file mode 100644 index 00000000..36f1577b --- /dev/null +++ b/ftplugin/latex-box/folding.vim @@ -0,0 +1,317 @@ +" Folding support for LaTeX +" +" Options +" g:LatexBox_Folding - Turn on/off folding +" g:LatexBox_fold_preamble - Turn on/off folding of preamble +" g:LatexBox_fold_parts - Define parts (eq. appendix, frontmatter) to fold +" g:LatexBox_fold_sections - Define section levels to fold +" g:LatexBox_fold_envs - Turn on/off folding of environments +" + +" {{{1 Set options +if exists('g:LatexBox_Folding') && g:LatexBox_Folding == 1 + setl foldmethod=expr + setl foldexpr=LatexBox_FoldLevel(v:lnum) + setl foldtext=LatexBox_FoldText() + " + " The foldexpr function returns "=" for most lines, which means it can become + " slow for large files. The following is a hack that is based on this reply to + " a discussion on the Vim Developer list: + " http://permalink.gmane.org/gmane.editors.vim.devel/14100 + " + augroup FastFold + autocmd! + autocmd InsertEnter *.tex setlocal foldmethod=manual + autocmd InsertLeave *.tex setlocal foldmethod=expr + augroup end +endif +if !exists('g:LatexBox_fold_preamble') + let g:LatexBox_fold_preamble=1 +endif +if !exists('g:LatexBox_fold_envs') + let g:LatexBox_fold_envs=1 +endif +if !exists('g:LatexBox_fold_parts') + let g:LatexBox_fold_parts=[ + \ "appendix", + \ "frontmatter", + \ "mainmatter", + \ "backmatter" + \ ] +endif +if !exists('g:LatexBox_fold_sections') + let g:LatexBox_fold_sections=[ + \ "part", + \ "chapter", + \ "section", + \ "subsection", + \ "subsubsection" + \ ] +endif +if !exists('g:LatexBox_fold_toc') + let g:LatexBox_fold_toc=0 +endif +if !exists('g:LatexBox_fold_toc_levels') + let g:LatexBox_fold_toc_levels=1 +endif + + +" {{{1 LatexBox_FoldLevel help functions + +" This function parses the tex file to find the sections that are to be folded +" and their levels, and then predefines the patterns for optimized folding. +function! s:FoldSectionLevels() + " Initialize + let level = 1 + let foldsections = [] + + " If we use two or more of the *matter commands, we need one more foldlevel + let nparts = 0 + for part in g:LatexBox_fold_parts + let i = 1 + while i < line("$") + if getline(i) =~ '^\s*\\' . part . '\>' + let nparts += 1 + break + endif + let i += 1 + endwhile + if nparts > 1 + let level = 2 + break + endif + endfor + + " Combine sections and levels, but ignore unused section commands: If we + " don't use the part command, then chapter should have the highest + " level. If we don't use the chapter command, then section should be the + " highest level. And so on. + let ignore = 1 + for part in g:LatexBox_fold_sections + " For each part, check if it is used in the file. We start adding the + " part patterns to the fold sections array whenever we find one. + let partpattern = '^\s*\(\\\|% Fake\)' . part . '\>' + if ignore + let i = 1 + while i < line("$") + if getline(i) =~# partpattern + call insert(foldsections, [partpattern, level]) + let level += 1 + let ignore = 0 + break + endif + let i += 1 + endwhile + else + call insert(foldsections, [partpattern, level]) + let level += 1 + endif + endfor + + return foldsections +endfunction + +" {{{1 LatexBox_FoldLevel + +" Parse file to dynamically set the sectioning fold levels +let b:LatexBox_FoldSections = s:FoldSectionLevels() + +" Optimize by predefine common patterns +let s:notbslash = '\%(\\\@1" + elseif line =~# '^\s*\\begin\s*{\s*document\s*}' + return "0" + endif + endif + + " Fold parts (\frontmatter, \mainmatter, \backmatter, and \appendix) + if line =~# s:foldparts + return ">1" + endif + + " Fold chapters and sections + for [part, level] in b:LatexBox_FoldSections + if line =~# part + return ">" . level + endif + endfor + + " Fold environments + if g:LatexBox_fold_envs == 1 + if line =~# s:envbeginpattern + return "a1" + elseif line =~# '^\s*\\end{document}' + " Never fold \end{document} + return 0 + elseif line =~# s:envendpattern + return "s1" + endif + endif + + " Return foldlevel of previous line + return "=" +endfunction + +" {{{1 LatexBox_FoldText help functions +function! s:LabelEnv() + let i = v:foldend + while i >= v:foldstart + if getline(i) =~ '^\s*\\label' + return matchstr(getline(i), '^\s*\\label{\zs.*\ze}') + end + let i -= 1 + endwhile + return "" +endfunction + +function! s:CaptionEnv() + let i = v:foldend + while i >= v:foldstart + if getline(i) =~ '^\s*\\caption' + return matchstr(getline(i), '^\s*\\caption\(\[.*\]\)\?{\zs.\+') + end + let i -= 1 + endwhile + return "" +endfunction + +function! s:CaptionTable() + let i = v:foldstart + while i <= v:foldend + if getline(i) =~ '^\s*\\caption' + return matchstr(getline(i), '^\s*\\caption\(\[.*\]\)\?{\zs.\+') + end + let i += 1 + endwhile + return "" +endfunction + +function! s:CaptionFrame(line) + " Test simple variants first + let caption1 = matchstr(a:line,'\\begin\*\?{.*}{\zs.\+\ze}') + let caption2 = matchstr(a:line,'\\begin\*\?{.*}{\zs.\+') + + if len(caption1) > 0 + return caption1 + elseif len(caption2) > 0 + return caption2 + else + let i = v:foldstart + while i <= v:foldend + if getline(i) =~ '^\s*\\frametitle' + return matchstr(getline(i), + \ '^\s*\\frametitle\(\[.*\]\)\?{\zs.\+') + end + let i += 1 + endwhile + + return "" + endif +endfunction + +" {{{1 LatexBox_FoldText +function! LatexBox_FoldText() + " Initialize + let line = getline(v:foldstart) + let nlines = v:foldend - v:foldstart + 1 + let level = '' + let title = 'Not defined' + + " Fold level + let level = strpart(repeat('-', v:foldlevel-1) . '*',0,3) + if v:foldlevel > 3 + let level = strpart(level, 1) . v:foldlevel + endif + let level = printf('%-3s', level) + + " Preamble + if line =~ '\s*\\documentclass' + let title = "Preamble" + endif + + " Parts, sections and fakesections + let sections = '\(\(sub\)*section\|part\|chapter\)' + let secpat1 = '^\s*\\' . sections . '\*\?\s*{' + let secpat2 = '^\s*\\' . sections . '\*\?\s*\[' + if line =~ '\\frontmatter' + let title = "Frontmatter" + elseif line =~ '\\mainmatter' + let title = "Mainmatter" + elseif line =~ '\\backmatter' + let title = "Backmatter" + elseif line =~ '\\appendix' + let title = "Appendix" + elseif line =~ secpat1 . '.*}' + let title = matchstr(line, secpat1 . '\zs.*\ze}') + elseif line =~ secpat1 + let title = matchstr(line, secpat1 . '\zs.*') + elseif line =~ secpat2 . '.*\]' + let title = matchstr(line, secpat2 . '\zs.*\ze\]') + elseif line =~ secpat2 + let title = matchstr(line, secpat2 . '\zs.*') + elseif line =~ 'Fake' . sections . ':' + let title = matchstr(line,'Fake' . sections . ':\s*\zs.*') + elseif line =~ 'Fake' . sections + let title = matchstr(line, 'Fake' . sections) + endif + + " Environments + if line =~ '\\begin' + " Capture environment name + let env = matchstr(line,'\\begin\*\?{\zs\w*\*\?\ze}') + + " Set caption based on type of environment + if env == 'frame' + let label = '' + let caption = s:CaptionFrame(line) + elseif env == 'table' + let label = s:LabelEnv() + let caption = s:CaptionTable() + else + let label = s:LabelEnv() + let caption = s:CaptionEnv() + endif + + " If no caption found, check for a caption comment + if caption == '' + let caption = matchstr(line,'\\begin\*\?{.*}\s*%\s*\zs.*') + endif + + " Create title based on caption and label + if caption . label == '' + let title = env + elseif label == '' + let title = printf('%-12s%s', env . ':', + \ substitute(caption, '}\s*$', '','')) + elseif caption == '' + let title = printf('%-12s%56s', env, '(' . label . ')') + else + let title = printf('%-12s%-30s %21s', env . ':', + \ strpart(substitute(caption, '}\s*$', '',''),0,34), + \ '(' . label . ')') + endif + endif + + let title = strpart(title, 0, 68) + return printf('%-3s %-68s #%5d', level, title, nlines) +endfunction + +" {{{1 Footer +" vim:fdm=marker:ff=unix:ts=4:sw=4 diff --git a/ftplugin/latex-box/latexmk.vim b/ftplugin/latex-box/latexmk.vim new file mode 100644 index 00000000..4ea3ff09 --- /dev/null +++ b/ftplugin/latex-box/latexmk.vim @@ -0,0 +1,442 @@ +" LaTeX Box latexmk functions + +" Options and variables {{{ + +if !exists('g:LatexBox_latexmk_options') + let g:LatexBox_latexmk_options = '' +endif +if !exists('g:LatexBox_latexmk_async') + let g:LatexBox_latexmk_async = 0 +endif +if !exists('g:LatexBox_latexmk_preview_continuously') + let g:LatexBox_latexmk_preview_continuously = 0 +endif +if !exists('g:LatexBox_output_type') + let g:LatexBox_output_type = 'pdf' +endif +if !exists('g:LatexBox_autojump') + let g:LatexBox_autojump = 0 +endif +if ! exists('g:LatexBox_quickfix') + let g:LatexBox_quickfix = 1 +endif + +" }}} + +" Process ID management (used for asynchronous and continuous mode) {{{ + +" A dictionary of latexmk PID's (basename: pid) +if !exists('g:latexmk_running_pids') + let g:latexmk_running_pids = {} +endif + +" Set PID {{{ +function! s:LatexmkSetPID(basename, pid) + let g:latexmk_running_pids[a:basename] = a:pid +endfunction +" }}} + +" kill_latexmk_process {{{ +function! s:kill_latexmk_process(pid) + if has('win32') + silent execute '!taskkill /PID ' . a:pid . ' /T /F' + else + if g:LatexBox_latexmk_async + " vim-server mode + let pids = [] + let tmpfile = tempname() + silent execute '!ps x -o pgid,pid > ' . tmpfile + for line in readfile(tmpfile) + let new_pid = matchstr(line, '^\s*' . a:pid . '\s\+\zs\d\+\ze') + if !empty(new_pid) + call add(pids, new_pid) + endif + endfor + call delete(tmpfile) + if !empty(pids) + silent execute '!kill ' . join(pids) + endif + else + " single background process + silent execute '!kill ' . a:pid + endif + endif + if !has('gui_running') + redraw! + endif +endfunction +" }}} + +" kill_all_latexmk_processes {{{ +function! s:kill_all_latexmk_processes() + for pid in values(g:latexmk_running_pids) + call s:kill_latexmk_process(pid) + endfor +endfunction +" }}} + +" }}} + +" Setup for vim-server {{{ +function! s:SIDWrap(func) + if !exists('s:SID') + let s:SID = matchstr(expand(''), '\zs\d\+_\ze.*$') + endif + return s:SID . a:func +endfunction + +function! s:LatexmkCallback(basename, status) + " Only remove the pid if not in continuous mode + if !g:LatexBox_latexmk_preview_continuously + call remove(g:latexmk_running_pids, a:basename) + call LatexBox_LatexErrors(a:status, a:basename) + endif +endfunction + +function! s:setup_vim_server() + if !exists('g:vim_program') + + " attempt autodetection of vim executable + let g:vim_program = '' + if has('win32') + " Just drop through to the default for windows + else + if match(&shell, '/\(bash\|zsh\)$') >= 0 + let ppid = '$PPID' + else + let ppid = '$$' + endif + + 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) + endif + + 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 +endfunction +" }}} + +" Latexmk {{{ + +function! LatexBox_Latexmk(force) + " Define often used names + let basepath = LatexBox_GetTexBasename(1) + let basename = fnamemodify(basepath, ':t') + let texroot = shellescape(LatexBox_GetTexRoot()) + let mainfile = fnameescape(fnamemodify(LatexBox_GetMainTexFile(), ':t')) + + " Check if already running + if has_key(g:latexmk_running_pids, basepath) + echomsg "latexmk is already running for `" . basename . "'" + return + endif + + " Set wrap width in log file + let max_print_line = 2000 + if has('win32') + let env = 'set max_print_line=' . max_print_line . ' & ' + elseif match(&shell, '/tcsh$') >= 0 + let env = 'setenv max_print_line ' . max_print_line . '; ' + else + let env = 'max_print_line=' . max_print_line + endif + + " Set latexmk command with options + if has('win32') + " Make sure to switch drive as well as directory + let cmd = 'cd /D ' . texroot . ' && ' + else + let cmd = 'cd ' . texroot . ' && ' + endif + let cmd .= env . ' latexmk' + let cmd .= ' -' . g:LatexBox_output_type + let cmd .= ' -quiet ' + let cmd .= g:LatexBox_latexmk_options + if a:force + let cmd .= ' -g' + endif + if g:LatexBox_latexmk_preview_continuously + let cmd .= ' -pvc' + endif + let cmd .= ' -e ' . shellescape('$pdflatex =~ s/ / -file-line-error /') + let cmd .= ' -e ' . shellescape('$latex =~ s/ / -file-line-error /') + let cmd .= ' ' . mainfile + + " Redirect output to null + if has('win32') + let cmd .= ' >nul' + else + let cmd .= ' &>/dev/null' + endif + + if g:LatexBox_latexmk_async + " Check if VIM server exists + if empty(v:servername) + echoerr "cannot run latexmk in background without a VIM server" + echoerr "set g:LatexBox_latexmk_async to 0 to change compiling mode" + return + endif + + " Start vim server if necessary + call s:setup_vim_server() + + let setpidfunc = s:SIDWrap('LatexmkSetPID') + let callbackfunc = s:SIDWrap('LatexmkCallback') + if has('win32') + let vim_program = substitute(g:vim_program, + \ 'gvim\.exe$', 'vim.exe', '') + + " Define callback to set the pid + let callsetpid = setpidfunc . '(''' . basepath . ''', %CMDPID%)' + let vimsetpid = vim_program . ' --servername ' . v:servername + \ . ' --remote-expr ' . shellescape(callsetpid) + + " Define callback after latexmk is finished + let callback = callbackfunc . '(''' . basepath . ''', %LATEXERR%)' + let vimcmd = vim_program . ' --servername ' . v:servername + \ . ' --remote-expr ' . shellescape(callback) + + let asyncbat = tempname() . '.bat' + call writefile(['setlocal', + \ 'set T=%TEMP%\sthUnique.tmp', + \ 'wmic process where (Name="WMIC.exe" AND CommandLine LIKE "%%%TIME%%%") ' + \ . 'get ParentProcessId /value | find "ParentProcessId" >%T%', + \ 'set /P A=<%T%', + \ 'set CMDPID=%A:~16% & del %T%', + \ vimsetpid, + \ cmd, + \ 'set LATEXERR=%ERRORLEVEL%', + \ vimcmd, + \ 'endlocal'], asyncbat) + + " Define command + let cmd = '!start /b ' . asyncbat . ' & del ' . asyncbat + else + " Define callback to set the pid + let callsetpid = shellescape(setpidfunc).'"(\"'.basepath.'\",$$)"' + let vimsetpid = g:vim_program . ' --servername ' . v:servername + \ . ' --remote-expr ' . callsetpid + + " Define callback after latexmk is finished + let callback = shellescape(callbackfunc).'"(\"'.basepath.'\",$?)"' + let vimcmd = g:vim_program . ' --servername ' . v:servername + \ . ' --remote-expr ' . callback + + " Define command + " Note: Here we escape '%' because it may be given as a user option + " through g:LatexBox_latexmk_options, for instance with + " g:Latex..._options = "-pdflatex='pdflatex -synctex=1 \%O \%S'" + let cmd = vimsetpid . ' ; ' . escape(cmd, '%') . ' ; ' . vimcmd + let cmd = '! (' . cmd . ') >/dev/null &' + endif + + if g:LatexBox_latexmk_preview_continuously + echo 'Compiling to ' . g:LatexBox_output_type + \ . ' with continuous preview.' + else + echo 'Compiling to ' . g:LatexBox_output_type . ' ...' + endif + silent execute cmd + else + if g:LatexBox_latexmk_preview_continuously + if has('win32') + let cmd = '!start /b cmd /s /c "' . cmd . '"' + else + let cmd = '!' . cmd . ' &' + endif + echo 'Compiling to ' . g:LatexBox_output_type . ' ...' + silent execute cmd + + " Save PID in order to be able to kill the process when wanted. + if has('win32') + let tmpfile = tempname() + let pidcmd = 'cmd /c "wmic process where ' + \ . '(CommandLine LIKE "latexmk\%'.mainfile.'\%") ' + \ . 'get ProcessId /value | find "ProcessId" ' + \ . '>'.tmpfile.' "' + silent execute '! ' . pidcmd + let pids = readfile(tmpfile) + let pid = strpart(pids[0], 10) + let g:latexmk_running_pids[basepath] = pid + else + let pid = substitute(system('pgrep -f "perl.*' + \ . mainfile . '"'),'\D','','') + let g:latexmk_running_pids[basepath] = pid + endif + else + " Execute command and check for errors + echo 'Compiling to ' . g:LatexBox_output_type . ' ... (async off!)' + call system(cmd) + call LatexBox_LatexErrors(v:shell_error) + endif + endif + + " Redraw screen if necessary + if !has("gui_running") + redraw! + endif +endfunction +" }}} + +" LatexmkClean {{{ +function! LatexBox_LatexmkClean(cleanall) + let basename = LatexBox_GetTexBasename(1) + if has_key(g:latexmk_running_pids, basename) + echomsg "don't clean when latexmk is running" + return + endif + + if has('win32') + let cmd = 'cd /D ' . shellescape(LatexBox_GetTexRoot()) . ' & ' + else + let cmd = 'cd ' . shellescape(LatexBox_GetTexRoot()) . ';' + endif + if a:cleanall + let cmd .= 'latexmk -C ' + else + let cmd .= 'latexmk -c ' + endif + let cmd .= shellescape(LatexBox_GetMainTexFile()) + if has('win32') + let cmd .= ' >nul' + else + let cmd .= ' >&/dev/null' + endif + + call system(cmd) + if !has('gui_running') + redraw! + endif + + echomsg "latexmk clean finished" +endfunction +" }}} + +" LatexErrors {{{ +function! LatexBox_LatexErrors(status, ...) + if a:0 >= 1 + let log = a:1 . '.log' + else + let log = LatexBox_GetLogFile() + endif + + cclose + + " set cwd to expand error file correctly + let l:cwd = fnamemodify(getcwd(), ':p') + execute 'lcd ' . fnameescape(LatexBox_GetTexRoot()) + try + if g:LatexBox_autojump + execute 'cfile ' . fnameescape(log) + else + execute 'cgetfile ' . fnameescape(log) + endif + finally + " restore cwd + execute 'lcd ' . fnameescape(l:cwd) + endtry + + " Always open window if started by LatexErrors command + if a:status < 0 + botright copen + else + " Write status message to screen + redraw + if a:status > 0 || len(getqflist())>1 + echomsg 'Compiling to ' . g:LatexBox_output_type . ' ... failed!' + else + echomsg 'Compiling to ' . g:LatexBox_output_type . ' ... success!' + endif + + " Only open window when an error/warning is detected + if g:LatexBox_quickfix + belowright cw + if g:LatexBox_quickfix==2 + wincmd p + endif + endif + endif +endfunction +" }}} + +" LatexmkStatus {{{ +function! LatexBox_LatexmkStatus(detailed) + if a:detailed + if empty(g:latexmk_running_pids) + echo "latexmk is not running" + else + let plist = "" + for [basename, pid] in items(g: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(g:latexmk_running_pids, basename) + echo "latexmk is running" + else + echo "latexmk is not running" + endif + endif +endfunction +" }}} + +" LatexmkStop {{{ +function! LatexBox_LatexmkStop(silent) + if empty(g:latexmk_running_pids) + if !a:silent + let basepath = LatexBox_GetTexBasename(1) + let basename = fnamemodify(basepath, ':t') + echoerr "latexmk is not running for `" . basename . "'" + endif + else + let basepath = LatexBox_GetTexBasename(1) + let basename = fnamemodify(basepath, ':t') + if has_key(g:latexmk_running_pids, basepath) + call s:kill_latexmk_process(g:latexmk_running_pids[basepath]) + call remove(g:latexmk_running_pids, basepath) + if !a:silent + echomsg "latexmk stopped for `" . basename . "'" + endif + elseif !a:silent + echoerr "latexmk is not running for `" . basename . "'" + endif + endif +endfunction +" }}} + +" Commands {{{ + +command! -bang Latexmk call LatexBox_Latexmk( == "!") +command! -bang LatexmkClean call LatexBox_LatexmkClean( == "!") +command! -bang LatexmkStatus call LatexBox_LatexmkStatus( == "!") +command! LatexmkStop call LatexBox_LatexmkStop(0) +command! LatexErrors call LatexBox_LatexErrors(-1) + +if g:LatexBox_latexmk_async || g:LatexBox_latexmk_preview_continuously + autocmd BufUnload call LatexBox_LatexmkStop(1) + autocmd VimLeave * call kill_all_latexmk_processes() +endif + +" }}} + +" vim:fdm=marker:ff=unix:noet:ts=4:sw=4 diff --git a/ftplugin/latex-box/mappings.vim b/ftplugin/latex-box/mappings.vim new file mode 100644 index 00000000..509f5f19 --- /dev/null +++ b/ftplugin/latex-box/mappings.vim @@ -0,0 +1,96 @@ +" LaTeX Box mappings + +if exists("g:LatexBox_no_mappings") + finish +endif + +" latexmk {{{ +map ll :Latexmk +map lL :Latexmk! +map lc :LatexmkClean +map lC :LatexmkClean! +map lg :LatexmkStatus +map lG :LatexmkStatus! +map lk :LatexmkStop +map le :LatexErrors +" }}} + +" View {{{ +map lv :LatexView +" }}} + +" TOC {{{ +map lt :LatexTOC +" }}} + +" Jump to match {{{ +if !exists('g:LatexBox_loaded_matchparen') + nmap % LatexBox_JumpToMatch + vmap % LatexBox_JumpToMatch + omap % LatexBox_JumpToMatch +endif +" }}} + +" Define text objects {{{ +vmap ie LatexBox_SelectCurrentEnvInner +vmap ae LatexBox_SelectCurrentEnvOuter +omap ie :normal vie +omap ae :normal vae +vmap i$ LatexBox_SelectInlineMathInner +vmap a$ LatexBox_SelectInlineMathOuter +omap i$ :normal vi$ +omap a$ :normal va$ +" }}} + +" Jump between sections {{{ +function! s:LatexBoxNextSection(type, backwards, visual) + " Restore visual mode if desired + if a:visual + normal! gv + endif + + " For the [] and ][ commands we move up or down before the search + if a:type == 1 + if a:backwards + normal! k + else + normal! j + endif + endif + + " Define search pattern and do the search while preserving "/ + let save_search = @/ + let flags = 'W' + if a:backwards + let flags = 'b' . flags + endif + let notcomment = '\%(\%(\\\@' + call search(pattern, flags) + let @/ = save_search + + " For the [] and ][ commands we move down or up after the search + if a:type == 1 + if a:backwards + normal! j + else + normal! k + endif + endif +endfunction +noremap ]] :call LatexBoxNextSection(0,0,0) +noremap ][ :call LatexBoxNextSection(1,0,0) +noremap [] :call LatexBoxNextSection(1,1,0) +noremap [[ :call LatexBoxNextSection(0,1,0) +vnoremap ]] :call LatexBoxNextSection(0,0,1) +vnoremap ][ :call LatexBoxNextSection(1,0,1) +vnoremap [] :call LatexBoxNextSection(1,1,1) +vnoremap [[ :call LatexBoxNextSection(0,1,1) +" }}} + +" vim:fdm=marker:ff=unix:noet:ts=4:sw=4 diff --git a/ftplugin/latex-box/motion.vim b/ftplugin/latex-box/motion.vim new file mode 100644 index 00000000..58a6fb42 --- /dev/null +++ b/ftplugin/latex-box/motion.vim @@ -0,0 +1,518 @@ +" LaTeX Box motion functions + +" Motion options {{{ +" Opening and closing patterns +if !exists('g:LatexBox_open_pats') + let g:LatexBox_open_pats = [ '\\{','{','\\(','(','\\\[','\[', + \ '\\begin\s*{.\{-}}', '\\left\s*\%([^\\]\|\\.\|\\\a*\)'] + let g:LatexBox_close_pats = [ '\\}','}','\\)',')','\\\]','\]', + \ '\\end\s*{.\{-}}', '\\right\s*\%([^\\]\|\\.\|\\\a*\)'] +endif +" }}} + +" 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 +" }}} + +" Finding Matching Pair {{{ +function! s:FindMatchingPair(mode) + + if a:mode =~ 'h\|i' + 2match none + elseif a:mode == 'v' + normal! gv + endif + + if LatexBox_InComment() | return | endif + + " open/close pairs (dollars signs are treated apart) + let dollar_pat = '\$' + let notbslash = '\%(\\\@1 && a:mode =~ 'o' + call cursor(lnum2, matchend(getline('.'), '\C' + \ . close_pat, col('.')-1)) + endif + endif + break + elseif delim =~# '^' . close_pat + " if on closing pattern, search for opening pattern + let [lnum2, cnum2] = searchpairpos('\C' . open_pat, '', + \ '\C\%(\%'. lnum . 'l\%' . cnum . 'c\)\@!' + \ . close_pat, 'bnW', 'LatexBox_InComment()', + \ line('w0')*(a:mode =~ 'h\|i') , 200) + if a:mode =~ 'h\|i' + execute '2match MatchParen /\%(\%' . lnum2 . 'l\%' . cnum2 + \ . 'c' . g:LatexBox_open_pats[i] . '\|\%' + \ . lnum . 'l\%' . cnum . 'c' + \ . g:LatexBox_close_pats[i] . '\)/' + elseif a:mode =~ 'n\|v\|o' + call cursor(lnum2,cnum2) + endif + break + endif + endfor + + endif +endfunction + +" Allow to disable functionality if desired +if !exists('g:LatexBox_loaded_matchparen') + " Disable matchparen autocommands + augroup LatexBox_HighlightPairs + autocmd BufEnter * if !exists("g:loaded_matchparen") || !g:loaded_matchparen | runtime plugin/matchparen.vim | endif + autocmd BufEnter *.tex 3match none | unlet! g:loaded_matchparen | au! matchparen + autocmd! CursorMoved *.tex call s:FindMatchingPair('h') + autocmd! CursorMovedI *.tex call s:FindMatchingPair('i') + augroup END +endif + +" Use LatexBox'es FindMatchingPair as '%' (enable jump between e.g. $'s) +nnoremap LatexBox_JumpToMatch :call FindMatchingPair('n') +vnoremap LatexBox_JumpToMatch :call FindMatchingPair('v') +onoremap LatexBox_JumpToMatch v:call FindMatchingPair('o') + +" }}} + +" select inline math {{{ +" s:SelectInlineMath(seltype) +" where seltype is either 'inner' or 'outer' +function! s:SelectInlineMath(seltype) + + let dollar_pat = '\\\@ LatexBox_SelectInlineMathInner + \ :call SelectInlineMath('inner') +vnoremap LatexBox_SelectInlineMathOuter + \ :call SelectInlineMath('outer') +" }}} + +" 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 +vnoremap LatexBox_SelectCurrentEnvInner :call SelectCurrentEnv('inner') +vnoremap LatexBox_SelectCurrentEnvOuter :call SelectCurrentEnv('outer') +" }}} + +" 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 +" }}} + +" Table of Contents {{{ + +" Special UTF-8 conversion +function! s:ConvertBack(line) + let line = a:line + if !exists('g:LatexBox_plaintext_toc') + let line = substitute(line, "\\\\IeC\s*{\\\\'a}", 'á', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\`a}", 'à', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\^a}", 'à', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\¨a}", 'ä', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\\"a}", 'ä', 'g') + + let line = substitute(line, "\\\\IeC\s*{\\\\'e}", 'é', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\`e}", 'è', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\^e}", 'ê', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\¨e}", 'ë', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\\"e}", 'ë', 'g') + + let line = substitute(line, "\\\\IeC\s*{\\\\'i}", 'í', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\`i}", 'î', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\^i}", 'ì', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\¨i}", 'ï', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\\"i}", 'ï', 'g') + + let line = substitute(line, "\\\\IeC\s*{\\\\'o}", 'ó', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\`o}", 'ò', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\^o}", 'ô', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\¨o}", 'ö', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\\"o}", 'ö', 'g') + + let line = substitute(line, "\\\\IeC\s*{\\\\'u}", 'ú', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\`u}", 'ù', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\^u}", 'û', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\¨u}", 'ü', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\\"u}", 'ü', 'g') + + let line = substitute(line, "\\\\IeC\s*{\\\\'A}", 'Ã', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\`A}", 'À', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\^A}", 'À', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\¨A}", 'Ä', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\\"A}", 'Ä', 'g') + + let line = substitute(line, "\\\\IeC\s*{\\\\'E}", 'É', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\`E}", 'È', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\^E}", 'Ê', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\¨E}", 'Ë', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\\"E}", 'Ë', 'g') + + let line = substitute(line, "\\\\IeC\s*{\\\\'I}", 'Ã', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\`I}", 'ÃŽ', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\^I}", 'ÃŒ', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\¨I}", 'Ã', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\\"I}", 'Ã', 'g') + + let line = substitute(line, "\\\\IeC\s*{\\\\'O}", 'Ó', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\`O}", 'Ã’', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\^O}", 'Ô', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\¨O}", 'Ö', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\\"O}", 'Ö', 'g') + + let line = substitute(line, "\\\\IeC\s*{\\\\'U}", 'Ú', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\`U}", 'Ù', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\^U}", 'Û', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\¨U}", 'Ü', 'g') + let line = substitute(line, "\\\\IeC\s*{\\\\\"U}", 'Ü', 'g') + else + " substitute stuff like '\IeC{\"u}' (utf-8 umlauts in section heading) + " to plain 'u' + let line = substitute(line, "\\\\IeC\s*{\\\\.\\(.\\)}", '\1', 'g') + endif + return line +endfunction + +function! s:ReadTOC(auxfile, texfile, ...) + let texfile = a:texfile + let prefix = fnamemodify(a:auxfile, ':p:h') + + if a:0 != 2 + let toc = [] + let fileindices = { texfile : [] } + else + let toc = a:1 + let fileindices = a:2 + let fileindices[ texfile ] = [] + endif + + for line in readfile(a:auxfile) + let included = matchstr(line, '^\\@input{\zs[^}]*\ze}') + if included != '' + " append the input TOX to `toc` and `fileindices` + let newaux = prefix . '/' . included + let newtex = fnamemodify(fnamemodify(newaux, ':t:r') . '.tex', ':p') + call s:ReadTOC(newaux, newtex, toc, fileindices) + continue + endif + + " Parse statements like: + " \@writefile{toc}{\contentsline {section}{\numberline {secnum}Section Title}{pagenumber}} + " \@writefile{toc}{\contentsline {section}{\tocsection {}{1}{Section Title}}{pagenumber}} + " \@writefile{toc}{\contentsline {section}{\numberline {secnum}Section Title}{pagenumber}{otherstuff}} + + let line = matchstr(line, + \ '\\@writefile{toc}{\\contentsline\s*\zs.*\ze}\s*$') + if empty(line) + continue + endif + + let tree = LatexBox_TexToTree(line) + + if len(tree) < 3 + " unknown entry type: just skip it + continue + endif + + " parse level + let level = tree[0][0] + " parse page + if !empty(tree[2]) + let page = tree[2][0] + else + let page = '' + endif + " parse section number + if len(tree[1]) > 3 && empty(tree[1][1]) + call remove(tree[1], 1) + endif + if len(tree[1]) > 1 + if !empty(tree[1][1]) + let secnum = LatexBox_TreeToTex(tree[1][1]) + let secnum = s:ConvertBack(secnum) + let secnum = substitute(secnum, '\\\S\+\s', '', 'g') + let secnum = substitute(secnum, '\\\S\+{\(.\{-}\)}', '\1', 'g') + let secnum = substitute(secnum, '^{\+\|}\+$', '', 'g') + endif + let tree = tree[1][2:] + else + let secnum = '' + let tree = tree[1] + endif + " parse section title + let text = LatexBox_TreeToTex(tree) + let text = s:ConvertBack(text) + let text = substitute(text, '^{\+\|}\+$', '', 'g') + + " add TOC entry + call add(fileindices[texfile], len(toc)) + call add(toc, {'file': texfile, + \ 'level': level, + \ 'number': secnum, + \ 'text': text, + \ 'page': page}) + endfor + + return [toc, fileindices] + +endfunction + +function! LatexBox_TOC(...) + + " Check if window already exists + let winnr = bufwinnr(bufnr('LaTeX TOC')) + if winnr >= 0 + if a:0 == 0 + silent execute winnr . 'wincmd w' + else + " Supplying an argument to this function causes toggling instead + " of jumping to the TOC window + if g:LatexBox_split_resize + silent exe "set columns-=" . g:LatexBox_split_width + endif + silent execute 'bwipeout' . bufnr('LaTeX TOC') + endif + return + endif + + " Read TOC + let [toc, fileindices] = s:ReadTOC(LatexBox_GetAuxFile(), + \ LatexBox_GetMainTexFile()) + let calling_buf = bufnr('%') + + " Find closest section in current buffer + let closest_index = s:FindClosestSection(toc,fileindices) + + " Create TOC window and set local settings + if g:LatexBox_split_resize + silent exe "set columns+=" . g:LatexBox_split_width + endif + silent exe g:LatexBox_split_side g:LatexBox_split_width . 'vnew LaTeX\ TOC' + let b:toc = toc + let b:toc_numbers = 1 + let b:calling_win = bufwinnr(calling_buf) + setlocal filetype=latextoc + + " Add TOC entries and jump to the closest section + for entry in toc + call append('$', entry['number'] . "\t" . entry['text']) + endfor + if !g:LatexBox_toc_hidehelp + call append('$', "") + call append('$', "/q: close") + call append('$', ": jump") + call append('$', ": jump and close") + call append('$', "s: hide numbering") + endif + 0delete _ + + execute 'normal! ' . (closest_index + 1) . 'G' + + " Lock buffer + setlocal nomodifiable +endfunction + +" Binary search for the closest section +" return the index of the TOC entry +function! s:FindClosestSection(toc, fileindices) + let file = expand('%:p') + if !has_key(a:fileindices, file) + echoe 'Current file is not included in main tex file ' . LatexBox_GetMainTexFile() . '.' + endif + + let imax = len(a:fileindices[file]) + let imin = 0 + while imin < imax - 1 + let i = (imax + imin) / 2 + let tocindex = a:fileindices[file][i] + let entry = a:toc[tocindex] + let titlestr = entry['text'] + let titlestr = escape(titlestr, '\') + let titlestr = substitute(titlestr, ' ', '\\_\\s\\+', 'g') + let [lnum, cnum] = searchpos('\\' . entry['level'] . '\_\s*{' . titlestr . '}', 'nW') + if lnum + let imax = i + else + let imin = i + endif + endwhile + + return a:fileindices[file][imin] +endfunction +" }}} + +" TOC Command {{{ +command! LatexTOC call LatexBox_TOC() +command! LatexTOCToggle call LatexBox_TOC(1) +" }}} + +" vim:fdm=marker:ff=unix:noet:ts=4:sw=4 diff --git a/ftplugin/latex-suite/bibtex.vim b/ftplugin/latex-suite/bibtex.vim deleted file mode 100644 index 2cc81995..00000000 --- a/ftplugin/latex-suite/bibtex.vim +++ /dev/null @@ -1,265 +0,0 @@ -"============================================================================= -" File: bibtex.vim -" Function: BibT -" Author: Alan G Isaac -" modified by Srinath Avadhanula for latex-suite. -" License: Vim Charityware license. -"============================================================================= - -" Fields: -" Define what field type each letter denotes {{{ -" -let s:w_standsfor = 'address' -let s:a_standsfor = 'author' -let s:b_standsfor = 'booktitle' -let s:c_standsfor = 'chapter' -let s:d_standsfor = 'edition' -let s:e_standsfor = 'editor' -let s:h_standsfor = 'howpublished' -let s:i_standsfor = 'institution' -let s:k_standsfor = 'isbn' -let s:j_standsfor = 'journal' -let s:m_standsfor = 'month' -let s:n_standsfor = 'number' -let s:o_standsfor = 'organization' -let s:p_standsfor = 'pages' -let s:q_standsfor = 'publisher' -let s:r_standsfor = 'school' -let s:s_standsfor = 'series' -let s:t_standsfor = 'title' -let s:u_standsfor = 'type' -let s:v_standsfor = 'volume' -let s:y_standsfor = 'year' -let s:z_standsfor = 'note' - -" }}} -" Define the fields required for the various entry types {{{ -" -" s:{type}_required defines the required fields -" s:{type}_optional1 defines common optional fields -" s:{type}_optional2 defines uncommmon optional fields -" s:{type}_retval defines the first line of the formatted bib entry. -" -let s:key='<+key+>' - -let s:{'article'}_required="atjy" -let s:{'article'}_optional1="vnpm" -let s:{'article'}_optional2="z" " z is note -let s:{'article'}_retval = '@ARTICLE{' . s:key . ','."\n" - -let s:{'book'}_required="aetqy" " requires author *or* editor -let s:{'book'}_optional1="wd" -let s:{'book'}_optional2="vnsmz" " w is address, d is edition -let s:{'book'}_extras="k" " isbn -let s:{'book'}_retval = '@BOOK{' . s:key . ','."\n" - -let s:{'booklet'}_required="t" -let s:{'booklet'}_optional1="ahy" -let s:{'booklet'}_optional2="wmz" " w is address -let s:{'booklet'}_retval = '@BOOKLET{' . s:key . ','."\n" - -let s:{'inbook'}_required="aetcpqy" -let s:{'inbook'}_optional1="w" " w is address -let s:{'inbook'}_optional2="vnsudmz" " d is edition -let s:{'inbook'}_extras="k" " isbn -let s:{'inbook'}_retval = '@INBOOK{' . s:key . ','."\n" - -let s:{'incollection'}_required="atbqy" " b is booktitle -let s:{'incollection'}_optional1="cpw" " w is address, c is chapter -let s:{'incollection'}_optional2="evnsudmz" " d is edition -let s:{'incollection'}_extras="k" " isbn -let s:{'incollection'}_retval = '@INCOLLECTION{' . s:key . ','."\n" - -let s:{'inproceedings'}_required="atby" " b is booktitle -let s:{'inproceedings'}_optional1="epwoq" " w is address, q is publisher -let s:{'inproceedings'}_optional2="vnsmz" -let s:{'inproceedings'}_extras="k" " isbn -let s:{'inproceedings'}_retval = '@INPROCEEDINGS{' . s:key . ','."\n" - -let s:{'conference'}_required="atby" " b is booktitle -let s:{'conference'}_optional1="epwoq" " w is address, q is publisher -let s:{'conference'}_optional2="vnsmz" -let s:{'conference'}_extras="k" " isbn -let s:{'conference'}_retval = '@CONFERENCE{' . s:key . ','."\n" - -let s:{'manual'}_required="t" -let s:{'manual'}_optional1="ow" -let s:{'manual'}_optional2="admyz" " w is address -let s:{'manual'}_retval = '@MANUAL{' . s:key . ','."\n" - -let s:{'msthesis'}_required="atry" " r is school -let s:{'msthesis'}_optional1="w" " w is address -let s:{'msthesis'}_optional2="umz" " u is type, w is address -let s:{'msthesis'}_retval = '@MASTERSTHESIS{' . s:key . ','."\n" - -let s:{'misc'}_required="" -let s:{'misc'}_optional1="ath" -let s:{'misc'}_optional2="myz" -let s:{'misc'}_retval = '@MISC{' . s:key . ','."\n" - -let s:{'phdthesis'}_required="atry" " r is school -let s:{'phdthesis'}_optional1="w" " w is address -let s:{'phdthesis'}_optional2="umz" " u is type -let s:{'phdthesis'}_retval = '@PHDTHESIS{' . s:key . ','."\n" - -let s:{'proceedings'}_required="ty" -let s:{'proceedings'}_optional1="ewo" " w is address -let s:{'proceedings'}_optional2="vnsmqz" " q is publisher -let s:{'proceedings'}_retval = '@PROCEEDINGS{' . s:key . ','."\n" - -let s:{'techreport'}_required="atiy" -let s:{'techreport'}_optional1="unw" " u is type, w is address -let s:{'techreport'}_optional2="mz" -let s:{'techreport'}_retval = '@TECHREPORT{' . s:key . ','."\n" - -let s:{'unpublished'}_required="atz" -let s:{'unpublished'}_optional1="y" -let s:{'unpublished'}_optional2="m" -let s:{'unpublished'}_retval = '@UNPUBLISHED{' . s:key . ','."\n" - -" }}} - -if exists('s:done') - finish -endif -let s:done = 1 - -call IMAP ('BBB', "\=BibT('', '', 0)\", 'bib') -call IMAP ('BBL', "\=BibT('', 'o', 0)\", 'bib') -call IMAP ('BBH', "\=BibT('', 'O', 0)\", 'bib') -call IMAP ('BBX', "\=BibT('', 'Ox', 0)\", 'bib') - -" BibT: function to generate a formatted bibtex entry {{{ -" three sample usages: -" :call BibT() will request type choice -" :call BibT("article") preferred, provides most common fields -" :call BibT("article","ox") more optional fields (o) and extras (x) -" -" Input Arguments: -" type: is one of the types listed above. (this should be a complete name, not -" the acronym). -" options: a string containing 0 or more of the letters 'oOx' -" where -" o: include a bib entry with first set of options -" O: include a bib entry with extended options -" x: incude bib entry with extra options -" prompt: whether the fields are asked to be filled on the command prompt or -" whether place-holders are used. when prompt == 1, then comman line -" questions are used. -" -" Returns: -" a string containing a formatted bib entry -function BibT(type, options, prompt) - if a:type != '' - let choosetype = a:type - else - let types = - \ 'article'."\n". - \ 'booklet'."\n". - \ 'book'."\n". - \ 'conference'."\n". - \ 'inbook'."\n". - \ 'incollection'."\n". - \ 'inproceedings'."\n". - \ 'manual'."\n". - \ 'msthesis'."\n". - \ 'misc'."\n". - \ 'phdthesis'."\n". - \ 'proceedings'."\n". - \ 'techreport'."\n". - \ 'unpublished' - let choosetype = Tex_ChooseFromPrompt( - \ "Choose the type of bibliographic entry: \n" . - \ Tex_CreatePrompt(types, 3, "\n") . - \ "\nEnter number or filename :", - \ types, "\n") - if choosetype == '' - let choosetype = 'article' - endif - if types !~ '^\|\n'.choosetype.'$\|\n' - echomsg 'Please choose only one of the given types' - return - endif - endif - if a:options != '' - let options = a:options - else - let options = "" - endif - - let fields = '' - let extras="" - let retval = "" - - " define fields - let fields = s:{choosetype}_required - if options =~ 'o' && exists('s:'.choosetype.'_optional1') - let fields = fields . s:{choosetype}_optional1 - endif - if options =~ "O" && exists('s:'.choosetype.'_optional2') - if options !~ 'o'&& exists('s:'.choosetype.'_optional1') - let fields = fields . s:{choosetype}_optional1 - endif - let fields = fields . s:{choosetype}_optional2 - endif - if options =~ "x" && exists('s:'.choosetype.'_extras') - let fields = fields . extras - endif - if exists('g:Bib_'.choosetype.'_options') - let fields = fields . g:Bib_{choosetype}_options - endif - - let retval = s:{choosetype}_retval - - let i = 0 - while i < strlen(fields) - let field = strpart(fields, i, 1) - - if exists('s:'.field.'_standsfor') - let field_name = s:{field}_standsfor - let retval = retval.field_name." = {<++>},\n" - endif - - let i = i + 1 - endwhile - - " If the user wants even more fine-tuning... - if Tex_GetVarValue('Bib_'.choosetype.'_extrafields') != '' - - let extrafields = Tex_GetVarValue('Bib_'.choosetype.'_extrafields') - - let i = 1 - while 1 - let field_name = Tex_Strntok(extrafields, "\n", i) - if field_name == '' - break - endif - - let retval = retval.field_name." = {<++>},\n" - - let i = i + 1 - endwhile - - endif - - let retval = retval.'otherinfo = {<++>}'."\n" - let retval = retval."}<++>"."\n" - - return IMAP_PutTextWithMovement(retval) -endfunction - -" }}} -function! s:Input(prompt, ask) " {{{ - if a:ask == 1 - let retval = input(a:prompt) - if retval == '' - return "<++>" - endif - else - return "<++>" - endif -endfunction - -" }}} - -" vim:fdm=marker:ff=unix:noet:ts=4:sw=4 diff --git a/ftplugin/latex-suite/brackets.vim b/ftplugin/latex-suite/brackets.vim deleted file mode 100644 index e1d69ae7..00000000 --- a/ftplugin/latex-suite/brackets.vim +++ /dev/null @@ -1,144 +0,0 @@ -" ============================================================================== -" History: This was originally part of auctex.vim by Carl Mueller. -" Srinath Avadhanula incorporated it into latex-suite with -" significant modifications. -" Parts of this file may be copyrighted by others as noted. -" Description: -" This ftplugin provides the following maps: -" . encloses the previous character in \mathbf{} -" . is polymorphic as follows: -" Insert mode: -" 1. If the previous character is a letter or number, then capitalize it and -" enclose it in \mathcal{} -" 2. otherwise insert \cite{} -" Visual Mode: -" 1. Enclose selection in \mathcal{} -" . is also polymorphic as follows: -" If the character before typing is one of '([{| \left(\right -" similarly for [, | -" { \left\{\right\} -" 2. < \langle\rangle -" 3. q \lefteqn{} -" otherwise insert \label{} -" . inserts \item commands at the current cursor location depending on -" the surrounding environment. For example, inside itemize, it will -" insert a simple \item, but within a description, it will insert -" \item[<+label+>] etc. -" -" These functions make it extremeley easy to do all the \left \right stuff in -" latex. -" ============================================================================== - -" Avoid reinclusion. -if exists('b:did_brackets') - finish -endif -let b:did_brackets = 1 - -" define the funtions only once. -if exists('*Tex_MathBF') - finish -endif - -" Tex_MathBF: encloses te previous letter/number in \mathbf{} {{{ -" Description: -function! Tex_MathBF() - return "\\\mathbf{\}" -endfunction " }}} -" Tex_MathCal: enclose the previous letter/number in \mathcal {{{ -" Description: -" if the last character is not a letter/number, then insert \cite{} -function! Tex_MathCal() - let line = getline(line(".")) - let char = line[col(".")-2] - - if char =~ '[a-zA-Z0-9]' - return "\".'\mathcal{'.toupper(char).'}' - else - return IMAP_PutTextWithMovement('\cite{<++>}<++>') - endif -endfunction -" }}} -" Tex_LeftRight: maps in insert mode. {{{ -" Description: -" This is a polymorphic function, which maps the behaviour of in the -" following way: -" If the character before typing is one of '([{| \left(<++>\right<++> -" similarly for [, | -" { \left\{<++>\right\}<++> -" 2. < \langle<++>\rangle<++> -" 3. q \lefteqn{<++>}<++> -" otherwise insert \label{<++>}<++> -function! Tex_LeftRight() - let line = getline(line(".")) - let char = line[col(".")-2] - let previous = line[col(".")-3] - - let matchedbrackets = '()[]{}||' - if char =~ '(\|\[\|{\||' - let add = '' - if char =~ '{' - let add = "\\" - endif - let rhs = matchstr(matchedbrackets, char.'\zs.\ze') - return "\".IMAP_PutTextWithMovement('\left'.add.char.'<++>\right'.add.rhs.'<++>') - elseif char == '<' - return "\".IMAP_PutTextWithMovement('\langle <++>\rangle<++>') - elseif char == 'q' - return "\".IMAP_PutTextWithMovement('\lefteqn{<++>}<++>') - else - return IMAP_PutTextWithMovement('\label{<++>}<++>') - endif -endfunction " }}} -" Tex_PutLeftRight: maps in normal mode {{{ -" Description: -" Put \left...\right in front of the matched brackets. -function! Tex_PutLeftRight() - let previous = getline(line("."))[col(".") - 2] - let char = getline(line("."))[col(".") - 1] - if previous == '\' - if char == '{' - exe "normal ileft\\\l%iright\\\l%" - elseif char == '}' - exe "normal iright\\\l%ileft\\\l%" - endif - elseif char =~ '\[\|(' - exe "normal i\\left\l%i\\right\l%" - elseif char =~ '\]\|)' - exe "normal i\\right\l%i\\left\l%" - endif -endfunction " }}} - -" Provide 'd mapping for easy user customization. {{{ -inoremap Tex_MathBF =Tex_MathBF() -inoremap Tex_MathCal =Tex_MathCal() -inoremap Tex_LeftRight =Tex_LeftRight() -vnoremap Tex_MathBF `>a}` -vnoremap Tex_MathCal `>a}` -nnoremap Tex_LeftRight :call Tex_PutLeftRight() - -" }}} -" Tex_SetBracketingMaps: create mappings for the current buffer {{{ -function! Tex_SetBracketingMaps() - - call Tex_MakeMap('', 'Tex_MathBF', 'i', ' ') - call Tex_MakeMap('', 'Tex_MathCal', 'i', ' ') - call Tex_MakeMap('', 'Tex_LeftRight', 'i', ' ') - call Tex_MakeMap('', 'Tex_MathBF', 'v', ' ') - call Tex_MakeMap('', 'Tex_MathCal', 'v', ' ') - call Tex_MakeMap('', 'Tex_LeftRight', 'n', ' ') - -endfunction -" }}} - -augroup LatexSuite - au LatexSuite User LatexSuiteFileType - \ call Tex_Debug('brackets.vim: Catching LatexSuiteFileType event', 'brak') | - \ call Tex_SetBracketingMaps() -augroup END - -" vim:fdm=marker diff --git a/ftplugin/latex-suite/compiler.vim b/ftplugin/latex-suite/compiler.vim deleted file mode 100644 index 28213fab..00000000 --- a/ftplugin/latex-suite/compiler.vim +++ /dev/null @@ -1,874 +0,0 @@ -"============================================================================= -" File: compiler.vim -" Author: Srinath Avadhanula -" Created: Tue Apr 23 05:00 PM 2002 PST -" -" Description: functions for compiling/viewing/searching latex documents -"============================================================================= - -" Tex_SetTeXCompilerTarget: sets the 'target' for the next call to Tex_RunLaTeX() {{{ -function! Tex_SetTeXCompilerTarget(type, target) - call Tex_Debug("+Tex_SetTeXCompilerTarget: setting target to [".a:target."] for ".a:type."r", "comp") - - if a:target == '' - let target = Tex_GetVarValue('Tex_DefaultTargetFormat') - let target = input('Enter the target format for '.a:type.'r: ', target) - else - let target = a:target - endif - if target == '' - let target = 'dvi' - endif - - let targetRule = Tex_GetVarValue('Tex_'.a:type.'Rule_'.target) - - if targetRule != '' - if a:type == 'Compile' - let &l:makeprg = escape(targetRule, Tex_GetVarValue('Tex_EscapeChars')) - elseif a:type == 'View' - let s:viewer = targetRule - endif - let s:target = target - - elseif Tex_GetVarValue('Tex_'.a:type.'RuleComplete_'.target) != '' - let s:target = target - - elseif a:type == 'View' && has('macunix') - " On the mac, we can have empty view rules, so do not complain when - " both Tex_ViewRule_target and Tex_ViewRuleComplete_target are - " empty. On other platforms, we will complain... see below. - let s:target = target - - else - let s:origdir = fnameescape(getcwd()) - exe 'cd '.fnameescape(expand('%:p:h')) - if !Tex_GetVarValue('Tex_UseMakefile') || (glob('makefile*') == '' && glob('Makefile*') == '') - if has('gui_running') - call confirm( - \'No '.a:type.' rule defined for target '.target."\n". - \'Please specify a rule in $VIMRUNTIME/ftplugin/tex/texrc'."\n". - \' :help Tex_'.a:type.'Rule_format'."\n". - \'for more information', - \"&ok", 1, 'Warning') - else - call input( - \'No '.a:type.' rule defined for target '.target."\n". - \'Please specify a rule in $VIMRUNTIME/ftplugin/tex/texrc'."\n". - \' :help Tex_'.a:type.'Rule_format'."\n". - \'for more information' - \) - endif - else - echomsg 'Assuming target is for makefile' - let s:target = target - endif - exe 'cd '.s:origdir - endif -endfunction - -function! SetTeXTarget(...) - if a:0 < 1 - let target = Tex_GetVarValue('Tex_DefaultTargetFormat') - let target = input('Enter the target format for compiler and viewer: ', target) - else - let target = a:1 - endif - if target == '' - let target = 'dvi' - endif - - call Tex_SetTeXCompilerTarget('Compile', target) - call Tex_SetTeXCompilerTarget('View', target) -endfunction - -com! -nargs=1 TCTarget :call Tex_SetTeXCompilerTarget('Compile', ) -com! -nargs=1 TVTarget :call Tex_SetTeXCompilerTarget('View', ) -com! -nargs=? TTarget :call SetTeXTarget() - -" }}} -" Tex_CompileLatex: compiles the present file. {{{ -" Description: -function! Tex_CompileLatex() - if &ft != 'tex' - echo "calling Tex_RunLaTeX from a non-tex file" - return - end - - " close any preview windows left open. - pclose! - - let s:origdir = fnameescape(getcwd()) - - " Find the main file corresponding to this file. Always cd to the - " directory containing the file to avoid problems with the directory - " containing spaces. - " Latex on linux seems to be unable to handle file names with spaces at - " all! Therefore for the moment, do not attempt to handle spaces in the - " file name. - if exists('b:fragmentFile') - let mainfname = expand('%:p:t') - call Tex_CD(expand('%:p:h')) - else - let mainfname = Tex_GetMainFileName(':p:t') - call Tex_CD(Tex_GetMainFileName(':p:h')) - end - - call Tex_Debug('Tex_CompileLatex: getting mainfname = ['.mainfname.'] from Tex_GetMainFileName', 'comp') - - " if a makefile exists and the user wants to use it, then use that - " irrespective of whether *.latexmain exists or not. mainfname is still - " extracted from *.latexmain (if possible) log file name depends on the - " main file which will be compiled. - if Tex_GetVarValue('Tex_UseMakefile') && (glob('makefile') != '' || glob('Makefile') != '') - let _makeprg = &l:makeprg - call Tex_Debug("Tex_CompileLatex: using the makefile in the current directory", "comp") - let &l:makeprg = 'make $*' - if exists('s:target') - call Tex_Debug('Tex_CompileLatex: execing [make! '.s:target.']', 'comp') - exec 'make! '.s:target - else - call Tex_Debug('Tex_CompileLatex: execing [make!]', 'comp') - exec 'make!' - endif - let &l:makeprg = _makeprg - else - " If &makeprg has something like "$*.ps", it means that it wants the - " file-name without the extension... Therefore remove it. - if &makeprg =~ '\$\*\.\w\+' - let mainfname = fnamemodify(mainfname, ':r') - endif - call Tex_Debug('Tex_CompileLatex: execing [make! '.mainfname.']', 'comp') - exec 'make! '.mainfname - endif - redraw! - - exe 'cd '.s:origdir -endfunction " }}} -" Tex_RunLaTeX: compilation function {{{ -" this function runs the latex command on the currently open file. often times -" the file being currently edited is only a fragment being \input'ed into some -" master tex file. in this case, make a file called mainfile.latexmain in the -" directory containig the file. in other words, if the current file is -" ~/thesis/chapter.tex -" so that doing "latex chapter.tex" doesnt make sense, then make a file called -" main.tex.latexmain -" in the ~/thesis directory. this will then run "latex main.tex" when -" Tex_RunLaTeX() is called. -function! Tex_RunLaTeX() - call Tex_Debug('+Tex_RunLaTeX, b:fragmentFile = '.exists('b:fragmentFile'), 'comp') - - let dir = expand("%:p:h").'/' - let s:origdir = fnameescape(getcwd()) - call Tex_CD(expand("%:p:h")) - - let initTarget = s:target - - " first get the dependency chain of this format. - call Tex_Debug("Tex_RunLaTeX: compiling to target [".s:target."]", "comp") - - if Tex_GetVarValue('Tex_FormatDependency_'.s:target) != '' - let dependency = Tex_GetVarValue('Tex_FormatDependency_'.s:target) - if dependency !~ ','.s:target.'$' - let dependency = dependency.','.s:target - endif - else - let dependency = s:target - endif - - call Tex_Debug('Tex_RunLaTeX: getting dependency chain = ['.dependency.']', 'comp') - - " now compile to the final target format via each dependency. - let i = 1 - while Tex_Strntok(dependency, ',', i) != '' - let s:target = Tex_Strntok(dependency, ',', i) - - call Tex_SetTeXCompilerTarget('Compile', s:target) - call Tex_Debug('Tex_RunLaTeX: setting target to '.s:target, 'comp') - - if Tex_GetVarValue('Tex_MultipleCompileFormats') =~ '\<'.s:target.'\>' - call Tex_Debug("Tex_RunLaTeX: compiling file multiple times via Tex_CompileMultipleTimes", "comp") - call Tex_CompileMultipleTimes() - else - call Tex_Debug("Tex_RunLaTeX: compiling file once via Tex_CompileLatex", "comp") - call Tex_CompileLatex() - endif - - let errlist = Tex_GetErrorList() - call Tex_Debug("Tex_RunLaTeX: errlist = [".errlist."]", "comp") - - " If there are any errors, then break from the rest of the steps - if errlist =~ '\v(error|warning)' - call Tex_Debug('Tex_RunLaTeX: There were errors in compiling, breaking chain...', 'comp') - break - endif - - let i = i + 1 - endwhile - - let s:target = initTarget - let s:origwinnum = winnr() - call Tex_SetupErrorWindow() - - exe 'cd '.s:origdir - call Tex_Debug("-Tex_RunLaTeX", "comp") -endfunction - -" }}} -" Tex_ViewLaTeX: opens viewer {{{ -" Description: opens the DVI viewer for the file being currently edited. -" Again, if the current file is a \input in a master file, see text above -" Tex_RunLaTeX() to see how to set this information. -function! Tex_ViewLaTeX() - if &ft != 'tex' - echo "calling Tex_ViewLaTeX from a non-tex file" - return - end - - let s:origdir = fnameescape(getcwd()) - - " If b:fragmentFile is set, it means this file was compiled as a fragment - " using Tex_PartCompile, which means that we want to ignore any - " *.latexmain or makefile's. - if !exists('b:fragmentFile') - " cd to the location of the file to avoid having to deal with spaces - " in the directory name. - let mainfname = Tex_GetMainFileName(':p:t:r') - call Tex_CD(Tex_GetMainFileName(':p:h')) - else - let mainfname = expand("%:p:t:r") - call Tex_CD(expand("%:p:h")) - endif - - if Tex_GetVarValue('Tex_ViewRuleComplete_'.s:target) != '' - - let execString = Tex_GetVarValue('Tex_ViewRuleComplete_'.s:target) - let execString = substitute(execString, '{v:servername}', v:servername, 'g') - - elseif has('win32') - " unfortunately, yap does not allow the specification of an external - " editor from the command line. that would have really helped ensure - " that this particular vim and yap are connected. - let execString = 'start '.s:viewer.' "$*.'.s:target.'"' - - elseif (has('macunix') && Tex_GetVarValue('Tex_TreatMacViewerAsUNIX') != 1) - - if strlen(s:viewer) - let appOpt = '-a ' - else - let appOpt = '' - endif - let execString = 'open '.appOpt.s:viewer.' $*.'.s:target - - else - " taken from Dimitri Antoniou's tip on vim.sf.net (tip #225). - " slight change to actually use the current servername instead of - " hardcoding it as xdvi. - " Using an option for specifying the editor in the command line - " because that seems to not work on older bash'es. - if s:target == 'dvi' - - if Tex_GetVarValue('Tex_UseEditorSettingInDVIViewer') == 1 && - \ v:servername != '' && - \ s:viewer =~ '^ *xdvik\?\( \|$\)' - - let execString = s:viewer.' -editor "gvim --servername '.v:servername. - \ ' --remote-silent +\%l \%f" $*.dvi' - - elseif Tex_GetVarValue('Tex_UseEditorSettingInDVIViewer') == 1 && - \ s:viewer =~ '^ *kdvi\( \|$\)' - - let execString = s:viewer.' --unique $*.dvi' - - else - - let execString = s:viewer.' $*.dvi' - - endif - - else - - let execString = s:viewer.' $*.'.s:target - - endif - - if( Tex_GetVarValue('Tex_ExecuteUNIXViewerInForeground') != 1 ) - let execString = execString.' &' - endif - - end - - let execString = substitute(execString, '\V$*', mainfname, 'g') - call Tex_Debug("Tex_ViewLaTeX: execString = ".execString, "comp") - - exec 'silent! !'.execString - - if !has('gui_running') - redraw! - endif - - exe 'cd '.s:origdir -endfunction - -" }}} -" Tex_ForwardSearchLaTeX: searches for current location in dvi file. {{{ -" Description: if the DVI viewer is compatible, then take the viewer to that -" position in the dvi file. see docs for Tex_RunLaTeX() to set a -" master file if this is an \input'ed file. -" Tip: With YAP on Windows, it is possible to do forward and inverse searches -" on DVI files. to do forward search, you'll have to compile the file -" with the --src-specials option. then set the following as the command -" line in the 'view/options/inverse search' dialog box: -" gvim --servername LATEX --remote-silent +%l "%f" -" For inverse search, if you are reading this, then just pressing \ls -" will work. -function! Tex_ForwardSearchLaTeX() - if &ft != 'tex' - echo "calling Tex_ForwardSeachLaTeX from a non-tex file" - return - end - - if Tex_GetVarValue('Tex_ViewRule_'.s:target) == '' - return - endif - let viewer = Tex_GetVarValue('Tex_ViewRule_'.s:target) - - let s:origdir = fnameescape(getcwd()) - - let mainfname = Tex_GetMainFileName(':t') - let mainfnameRoot = fnamemodify(Tex_GetMainFileName(), ':t:r') - let mainfnameFull = Tex_GetMainFileName(':p:r') - " cd to the location of the file to avoid problems with directory name - " containing spaces. - call Tex_CD(Tex_GetMainFileName(':p:h')) - - " inverse search tips taken from Dimitri Antoniou's tip and Benji Fisher's - " tips on vim.sf.net (vim.sf.net tip #225) - if (has('win32') && (viewer =~? '^ *yap\( \|$\)')) - - let execString = 'silent! !start '. viewer.' -s '.line('.').expand('%').' '.mainfnameRoot - - - elseif (has('macunix') && (viewer =~ '^ *\(Skim\|PDFView\|TeXniscope\)\( \|$\)')) - " We're on a Mac using a traditional Mac viewer - - if viewer =~ '^ *Skim' - - let execString = 'silent! !/Applications/Skim.app/Contents/SharedSupport/displayline '. - \ line('.').' "'.mainfnameFull.'.'.s:target.'" "'.expand("%:p").'"' - - elseif viewer =~ '^ *PDFView' - - let execString = 'silent! !/Applications/PDFView.app/Contents/MacOS/gotoline.sh '. - \ line('.').' "'.mainfnameFull.'.'.s:target.'" "'.expand("%:p").'"' - - elseif viewer =~ '^ *TeXniscope' - - let execString = 'silent! !/Applications/TeXniscope.app/Contents/Resources/forward-search.sh '. - \ line('.').' "'.expand("%:p").'" "'.mainfnameFull.'.'.s:target.'"' - - endif - - else - " We're either UNIX or Mac and using a UNIX-type viewer - - " Check for the special DVI viewers first - if viewer =~ '^ *\(xdvi\|xdvik\|kdvi\|okular\)\( \|$\)' - - if Tex_GetVarValue('Tex_UseEditorSettingInDVIViewer') == 1 && - \ exists('v:servername') && - \ viewer =~ '^ *xdvik\?\( \|$\)' - - let execString = 'silent! !'.viewer.' -name xdvi -sourceposition "'.line('.').' '.expand("%").'"'. - \ ' -editor "gvim --servername '.v:servername.' --remote-silent +\%l \%f" '. - \ mainfnameRoot.'.dvi' - - elseif viewer =~ '^ *kdvi' - - let execString = 'silent! !'.viewer.' --unique file:'.mainfnameRoot.'.dvi\#src:'.line('.').expand("%") - - elseif viewer =~ '^ *xdvik\?\( \|$\)' - - let execString = 'silent! !'.viewer.' -name xdvi -sourceposition "'.line('.').' '.expand("%").'" '.mainfnameRoot.'.dvi' - - elseif viewer =~ '^ *okular' - - let execString = 'silent! !'.viewer.' --unique '.mainfnameRoot.'.'.s:target.'\#src:'.line('.').expand("%:p") - - endif - - else - " We must be using a generic UNIX viewer - " syntax is: viewer TARGET_FILE LINE_NUMBER SOURCE_FILE - - let execString = 'silent! !'.viewer.' "'.mainfnameRoot.'.'.s:target.'" '.line('.').' "'.expand('%').'"' - - endif - - " See if we should add &. On Mac (at least in MacVim), it seems - " like this should NOT be added... - if( Tex_GetVarValue('Tex_ExecuteUNIXViewerInForeground') != 1 ) - let execString = execString.' &' - endif - - endif - - call Tex_Debug("Tex_ForwardSearchLaTeX: execString = ".execString, "comp") - execute execString - if !has('gui_running') - redraw! - endif - - exe 'cd '.s:origdir -endfunction - -" }}} - -" ============================================================================== -" Functions for compiling parts of a file. -" ============================================================================== -" Tex_PartCompile: compiles selected fragment {{{ -" Description: creates a temporary file from the selected fragment of text -" prepending the preamble and \end{document} and then asks Tex_RunLaTeX() to -" compile it. -function! Tex_PartCompile() range - call Tex_Debug('+Tex_PartCompile', 'comp') - - " Get a temporary file in the same directory as the file from which - " fragment is being extracted. This is to enable the use of relative path - " names in the fragment. - let tmpfile = Tex_GetTempName(expand('%:p:h')) - - " Remember all the temp files and for each temp file created, remember - " where the temp file came from. - let s:Tex_NumTempFiles = (exists('s:Tex_NumTempFiles') ? s:Tex_NumTempFiles + 1 : 1) - let s:Tex_TempFiles = (exists('s:Tex_TempFiles') ? s:Tex_TempFiles : '') - \ . tmpfile."\n" - let s:Tex_TempFile_{s:Tex_NumTempFiles} = tmpfile - " TODO: For a function Tex_RestoreFragment which restores a temp file to - " its original location. - let s:Tex_TempFileOrig_{s:Tex_NumTempFiles} = expand('%:p') - let s:Tex_TempFileRange_{s:Tex_NumTempFiles} = a:firstline.','.a:lastline - - " Set up an autocmd to clean up the temp files when Vim exits. - if Tex_GetVarValue('Tex_RemoveTempFiles') - augroup RemoveTmpFiles - au! - au VimLeave * :call Tex_RemoveTempFiles() - augroup END - endif - - " If mainfile exists open it in tiny window and extract preamble there, - " otherwise do it from current file - let mainfile = Tex_GetMainFileName(":p") - exe 'bot 1 split '.escape(mainfile, ' ') - exe '1,/\s*\\begin{document}/w '.tmpfile - wincmd q - - exe a:firstline.','.a:lastline."w! >> ".tmpfile - - " edit the temporary file - exec 'drop '.tmpfile - - " append the \end{document} line. - $ put ='\end{document}' - w - - " set this as a fragment file. - let b:fragmentFile = 1 - - silent! call Tex_RunLaTeX() -endfunction " }}} -" Tex_RemoveTempFiles: cleans up temporary files created during part compilation {{{ -" Description: During part compilation, temporary files containing the -" visually selected text are created. These files need to be -" removed when Vim exits to avoid "file leakage". -function! Tex_RemoveTempFiles() - if !exists('s:Tex_NumTempFiles') || !Tex_GetVarValue('Tex_RemoveTempFiles') - return - endif - let i = 1 - while i <= s:Tex_NumTempFiles - let tmpfile = s:Tex_TempFile_{i} - " Remove the tmp file and all other associated files such as the - " .log files etc. - call Tex_DeleteFile(fnamemodify(tmpfile, ':p:r').'.*') - let i = i + 1 - endwhile -endfunction " }}} - -" ============================================================================== -" Compiling a file multiple times to resolve references/citations etc. -" ============================================================================== -" Tex_CompileMultipleTimes: The main function {{{ -" Description: compiles a file multiple times to get cross-references right. -function! Tex_CompileMultipleTimes() - " Just extract the root without any extension because we want to construct - " the log file names etc from it. - let s:origdir = fnameescape(getcwd()) - let mainFileName_root = Tex_GetMainFileName(':p:t:r') - call Tex_CD(Tex_GetMainFileName(':p:h')) - - " First ignore undefined references and the - " "rerun to get cross-references right" message from - " the compiler output. - let origlevel = Tex_GetVarValue('Tex_IgnoreLevel') - let origpats = Tex_GetVarValue('Tex_IgnoredWarnings') - - let g:Tex_IgnoredWarnings = g:Tex_IgnoredWarnings."\n" - \ . 'Reference %.%# undefined'."\n" - \ . 'Rerun to get cross-references right' - TCLevel 1000 - - let idxFileName = mainFileName_root.'.idx' - let auxFileName = mainFileName_root.'.aux' - - let runCount = 0 - let needToRerun = 1 - while needToRerun == 1 && runCount < 5 - " assume we need to run only once. - let needToRerun = 0 - - let idxlinesBefore = Tex_CatFile(idxFileName) - let auxlinesBefore = Tex_GetAuxFile(auxFileName) - - " first run latex. - echomsg "latex run number : ".(runCount+1) - call Tex_Debug("Tex_CompileMultipleTimes: latex run number : ".(runCount+1), "comp") - silent! call Tex_CompileLatex() - - " If there are errors in any latex compilation step, immediately - " return. For now, do not bother with warnings because those might go - " away after compiling again or after bibtex is run etc. - let errlist = Tex_GetErrorList() - call Tex_Debug("Tex_CompileMultipleTimes: errors = [".errlist."]", "comp") - - if errlist =~ 'error' - let g:Tex_IgnoredWarnings = origpats - exec 'TCLevel '.origlevel - - return - endif - - let idxlinesAfter = Tex_CatFile(idxFileName) - - " If .idx file changed, then run makeindex to generate the new .ind - " file and remember to rerun latex. - if runCount == 0 && glob(idxFileName) != '' && idxlinesBefore != idxlinesAfter - echomsg "Running makeindex..." - let temp_mp = &mp | let &mp = Tex_GetVarValue('Tex_MakeIndexFlavor') - exec 'silent! make '.mainFileName_root - let &mp = temp_mp - - let needToRerun = 1 - endif - - " The first time we see if we need to run bibtex and if the .bbl file - " changes, we will rerun latex. - if runCount == 0 && Tex_IsPresentInFile('\\bibdata', mainFileName_root.'.aux') - let bibFileName = mainFileName_root.'.bbl' - - let biblinesBefore = Tex_CatFile(bibFileName) - - echomsg "Running '".Tex_GetVarValue('Tex_BibtexFlavor')."' ..." - let temp_mp = &mp | let &mp = Tex_GetVarValue('Tex_BibtexFlavor') - exec 'silent! make '.mainFileName_root - let &mp = temp_mp - - let biblinesAfter = Tex_CatFile(bibFileName) - - " If the .bbl file changed after running bibtex, we need to - " latex again. - if biblinesAfter != biblinesBefore - echomsg 'Need to rerun because bibliography file changed...' - call Tex_Debug('Tex_CompileMultipleTimes: Need to rerun because bibliography file changed...', 'comp') - let needToRerun = 1 - endif - endif - - " check if latex asks us to rerun - let auxlinesAfter = Tex_GetAuxFile(auxFileName) - if auxlinesAfter != auxlinesBefore - echomsg "Need to rerun because the AUX file changed..." - call Tex_Debug("Tex_CompileMultipleTimes: Need to rerun to get cross-references right...", 'comp') - let needToRerun = 1 - endif - - let runCount = runCount + 1 - endwhile - - redraw! - call Tex_Debug("Tex_CompileMultipleTimes: Ran latex ".runCount." time(s)", "comp") - echomsg "Ran latex ".runCount." time(s)" - - let g:Tex_IgnoredWarnings = origpats - exec 'TCLevel '.origlevel - " After all compiler calls are done, reparse the .log file for - " errors/warnings to handle the situation where the clist might have been - " emptied because of bibtex/makeindex being run as the last step. - exec 'silent! cfile '.mainFileName_root.'.log' - - exe 'cd '.s:origdir -endfunction " }}} -" Tex_GetAuxFile: get the contents of the AUX file {{{ -" Description: get the contents of the AUX file recursively including any -" @\input'ted AUX files. -function! Tex_GetAuxFile(auxFile) - if !filereadable(a:auxFile) - return '' - endif - - let auxContents = Tex_CatFile(a:auxFile) - let pattern = '@\input{\(.\{-}\)}' - - let auxContents = substitute(auxContents, pattern, '\=Tex_GetAuxFile(submatch(1))', 'g') - - return auxContents -endfunction " }}} - -" ============================================================================== -" Helper functions for -" . viewing the log file in preview mode. -" . syncing the display between the quickfix window and preview window -" . going to the correct line _and column_ number from from the quick fix -" window. -" ============================================================================== -" Tex_SetupErrorWindow: sets up the cwindow and preview of the .log file {{{ -" Description: -function! Tex_SetupErrorWindow() - let mainfname = Tex_GetMainFileName() - - let winnum = winnr() - - " close the quickfix window before trying to open it again, otherwise - " whether or not we end up in the quickfix window after the :cwindow - " command is not fixed. - cclose - cwindow - " create log file name from mainfname - let mfnlog = fnamemodify(mainfname, ":t:r").'.log' - call Tex_Debug('Tex_SetupErrorWindow: mfnlog = '.mfnlog, 'comp') - " if we moved to a different window, then it means we had some errors. - if winnum != winnr() - if Tex_GetVarValue('Tex_ShowErrorContext') - call Tex_UpdatePreviewWindow(mfnlog) - exe 'nnoremap j j:call Tex_UpdatePreviewWindow("'.mfnlog.'")' - exe 'nnoremap k k:call Tex_UpdatePreviewWindow("'.mfnlog.'")' - exe 'nnoremap :call Tex_UpdatePreviewWindow("'.mfnlog.'")' - exe 'nnoremap :call Tex_UpdatePreviewWindow("'.mfnlog.'")' - endif - exe 'nnoremap :call Tex_GotoErrorLocation("'.mfnlog.'")' - - setlocal nowrap - - " resize the window to just fit in with the number of lines. - exec ( line('$') < 4 ? line('$') : 4 ).' wincmd _' - if Tex_GetVarValue('Tex_GotoError') == 1 - call Tex_GotoErrorLocation(mfnlog) - else - exec s:origwinnum.' wincmd w' - endif - endif - -endfunction " }}} -" Tex_PositionPreviewWindow: positions the preview window correctly. {{{ -" Description: -" The purpose of this function is to count the number of times an error -" occurs on the same line. or in other words, if the current line is -" something like |10 error|, then we want to count the number of -" lines in the quickfix window before this line which also contain lines -" like |10 error|. -" -function! Tex_PositionPreviewWindow(filename) - - if getline('.') !~ '|\d\+ \(error\|warning\)|' - if !search('|\d\+ \(error\|warning\)|') - call Tex_Debug("not finding error pattern anywhere in quickfix window :".bufname(bufnr('%')), - \ 'comp') - pclose! - return - endif - endif - - " extract the error pattern (something like 'file.tex|10 error|') on the - " current line. - let errpat = matchstr(getline('.'), '^\f*|\d\+ \(error\|warning\)|\ze') - let errfile = matchstr(getline('.'), '^\f*\ze|\d\+ \(error\|warning\)|') - " extract the line number from the error pattern. - let linenum = matchstr(getline('.'), '|\zs\d\+\ze \(error\|warning\)|') - - " if we are on an error, then count the number of lines before this in the - " quickfix window with an error on the same line. - if errpat =~ 'error|$' - " our location in the quick fix window. - let errline = line('.') - - " goto the beginning of the quickfix window and begin counting the lines - " which show an error on the same line. - 0 - let numrep = 0 - while 1 - " if we are on the same kind of error line, then means we have another - " line containing the same error pattern. - if getline('.') =~ errpat - let numrep = numrep + 1 - normal! 0 - endif - " if we have reached the original location in the quick fix window, - " then break. - if line('.') == errline - break - else - " otherwise, search for the next line which contains the same - " error pattern again. goto the end of the current line so we - " dont count this line again. - normal! $ - call search(errpat, 'W') - endif - endwhile - else - let numrep = 1 - endif - - if getline('.') =~ '|\d\+ warning|' - let searchpat = escape(matchstr(getline('.'), '|\d\+ warning|\s*\zs.*'), '\ ') - else - let searchpat = 'l\.'.linenum - endif - - " We first need to be in the scope of the correct file in the .log file. - " This is important for example, when a.tex and b.tex both have errors on - " line 9 of the file and we want to go to the error of b.tex. Merely - " searching forward from the beginning of the log file for l.9 will always - " land us on the error in a.tex. - if errfile != '' - exec 'silent! bot pedit +/(\\(\\f\\|\\[\\|\]\\|\\s\\)*'.errfile.'/ '.a:filename - else - exec 'bot pedit +0 '.a:filename - endif - " Goto the preview window - " TODO: This is not robust enough. Check that a wincmd j actually takes - " us to the preview window. - wincmd j - " now search forward from this position in the preview window for the - " numrep^th error of the current line in the quickfix window. - while numrep > 0 - call search(searchpat, 'W') - let numrep = numrep - 1 - endwhile - normal! z. - -endfunction " }}} -" Tex_UpdatePreviewWindow: updates the view of the log file {{{ -" Description: -" This function should be called when focus is in a quickfix window. -" It opens the log file in a preview window and makes it display that -" part of the log file which corresponds to the error which the user is -" currently on in the quickfix window. Control returns to the quickfix -" window when the function returns. -" -function! Tex_UpdatePreviewWindow(filename) - call Tex_PositionPreviewWindow(a:filename) - - if &previewwindow - 6 wincmd _ - wincmd p - endif -endfunction " }}} -" Tex_GotoErrorLocation: goes to the correct location of error in the tex file {{{ -" Description: -" This function should be called when focus is in a quickfix window. This -" function will first open the preview window of the log file (if it is not -" already open), position the display of the preview to coincide with the -" current error under the cursor and then take the user to the file in -" which this error has occured. -" -" The position is both the correct line number and the column number. -function! Tex_GotoErrorLocation(filename) - - " first use vim's functionality to take us to the location of the error - " accurate to the line (not column). This lets us go to the correct file - " without applying any logic. - exec "normal! \" - " If the log file is not found, then going to the correct line number is - " all we can do. - if glob(a:filename) == '' - return - endif - - let winnum = winnr() - " then come back to the quickfix window - wincmd w - - " find out where in the file we had the error. - let linenum = matchstr(getline('.'), '|\zs\d\+\ze \(warning\|error\)|') - call Tex_PositionPreviewWindow(a:filename) - - if getline('.') =~ 'l.\d\+' - - let brokenline = matchstr(getline('.'), 'l.'.linenum.' \zs.*\ze') - " If the line is of the form - " l.10 ...and then there was some error - " it means (most probably) that only part of the erroneous line is - " shown. In this case, finding the length of the broken line is not - " correct. Instead goto the beginning of the line and search forward - " for the part which is displayed and then go to its end. - if brokenline =~ '^\M...' - let partline = matchstr(brokenline, '^\M...\m\zs.*') - let normcmd = "0/\\V".escape(partline, "\\")."/e+1\" - else - let column = strlen(brokenline) + 1 - let normcmd = column.'|' - endif - - elseif getline('.') =~ 'LaTeX Warning: \(Citation\|Reference\) `.*' - - let ref = matchstr(getline('.'), "LaTeX Warning: \\(Citation\\|Reference\\) `\\zs[^']\\+\\ze'") - let normcmd = '0/'.ref."\" - - else - - let normcmd = '0' - - endif - - " go back to the window where we came from. - exec winnum.' wincmd w' - exec 'silent! '.linenum.' | normal! '.normcmd - - if !Tex_GetVarValue('Tex_ShowErrorContext') - pclose! - endif -endfunction " }}} -" Tex_SetCompilerMaps: sets maps for compiling/viewing/searching {{{ -" Description: -function! Tex_SetCompilerMaps() - if exists('b:Tex_doneCompilerMaps') - return - endif - let s:ml = '' - - nnoremap Tex_Compile :call Tex_RunLaTeX() - vnoremap Tex_Compile :call Tex_PartCompile() - nnoremap Tex_View :call Tex_ViewLaTeX() - nnoremap Tex_ForwardSearch :call Tex_ForwardSearchLaTeX() - - call Tex_MakeMap(s:ml."ll", "Tex_Compile", 'n', '') - call Tex_MakeMap(s:ml."ll", "Tex_Compile", 'v', '') - call Tex_MakeMap(s:ml."lv", "Tex_View", 'n', '') - call Tex_MakeMap(s:ml."ls", "Tex_ForwardSearch", 'n', '') -endfunction -" }}} - -augroup LatexSuite - au LatexSuite User LatexSuiteFileType - \ call Tex_Debug('compiler.vim: Catching LatexSuiteFileType event', 'comp') | - \ call Tex_SetCompilerMaps() -augroup END - -command! -nargs=0 -range=% TPartCompile :, silent! call Tex_PartCompile() -" Setting b:fragmentFile = 1 makes Tex_CompileLatex consider the present file -" the _main_ file irrespective of the presence of a .latexmain file. -command! -nargs=0 TCompileThis let b:fragmentFile = 1 -command! -nargs=0 TCompileMainFile let b:fragmentFile = 0 - -" vim:fdm=marker:ff=unix:noet:ts=4:sw=4 diff --git a/ftplugin/latex-suite/custommacros.vim b/ftplugin/latex-suite/custommacros.vim deleted file mode 100644 index a8482abb..00000000 --- a/ftplugin/latex-suite/custommacros.vim +++ /dev/null @@ -1,255 +0,0 @@ -"============================================================================= -" File: custommacros.vim -" Author: Mikolaj Machowski -" Version: 1.0 -" Created: Tue Apr 23 05:00 PM 2002 PST -" -" Description: functions for processing custom macros in the -" latex-suite/macros directory -"============================================================================= - -let s:path = expand(':p:h') - -" Set path to macros dir dependent on OS {{{ -if has("unix") || has("macunix") - let s:macrodirpath = $HOME."/.vim/ftplugin/latex-suite/macros/" -elseif has("win32") - if exists("$HOME") - let s:macrodirpath = $HOME."/vimfiles/ftplugin/latex-suite/macros/" - else - let s:macrodirpath = $VIM."/vimfiles/ftplugin/latex-suite/macros/" - endif -endif - -" }}} -" SetCustomMacrosMenu: sets up the menu for Macros {{{ -function! SetCustomMacrosMenu() - let flist = Tex_FindInRtp('', 'macros') - exe 'amenu '.g:Tex_MacrosMenuLocation.'&New :call NewMacro("FFFromMMMenu")' - exe 'amenu '.g:Tex_MacrosMenuLocation.'&Redraw :call RedrawMacro()' - - let i = 1 - while 1 - let fname = Tex_Strntok(flist, ',', i) - if fname == '' - break - endif - exe "amenu ".g:Tex_MacrosMenuLocation."&Delete.&".i.":".fname." :call DeleteMacro('".fname."')" - exe "amenu ".g:Tex_MacrosMenuLocation."&Edit.&".i.":".fname." :call EditMacro('".fname."')" - exe "imenu ".g:Tex_MacrosMenuLocation."&".i.":".fname." =ReadMacro('".fname."')" - exe "nmenu ".g:Tex_MacrosMenuLocation."&".i.":".fname." i=ReadMacro('".fname."')" - let i = i + 1 - endwhile -endfunction - -if g:Tex_Menus - call SetCustomMacrosMenu() -endif - -" }}} -" NewMacro: opens new file in macros directory {{{ -function! NewMacro(...) - " Allow for calling :TMacroNew without argument or from menu and prompt - " for name. - if a:0 > 0 - let newmacroname = a:1 - else - let newmacroname = input("Name of new macro: ") - if newmacroname == '' - return - endif - endif - - if newmacroname == "FFFromMMMenu" - " Check if NewMacro was called from menu and prompt for insert macro - " name - let newmacroname = input("Name of new macro: ") - if newmacroname == '' - return - endif - elseif Tex_FindInRtp(newmacroname, 'macros') != '' - " If macro with this name already exists, prompt for another name. - exe "echomsg 'Macro ".newmacroname." already exists. Try another name.'" - let newmacroname = input("Name of new macro: ") - if newmacroname == '' - return - endif - endif - exec 'split '.Tex_EscapeSpaces(s:macrodirpath.newmacroname) - setlocal filetype=tex -endfunction - -" }}} -" RedrawMacro: refreshes macro menu {{{ -function! RedrawMacro() - aunmenu TeX-Suite.Macros - call SetCustomMacrosMenu() -endfunction - -" }}} -" ChooseMacro: choose a macro file {{{ -" " Description: -function! s:ChooseMacro(ask) - let filelist = Tex_FindInRtp('', 'macros') - let filename = Tex_ChooseFromPrompt( - \ a:ask."\n" . - \ Tex_CreatePrompt(filelist, 2, ',') . - \ "\nEnter number or filename :", - \ filelist, ',') -endfunction - -" }}} -" DeleteMacro: deletes macro file {{{ -function! DeleteMacro(...) - if a:0 > 0 - let filename = a:1 - else - let filename = s:ChooseMacro('Choose a macro file for deletion :') - endif - - if !filereadable(s:macrodirpath.filename) - " When file is not in local directory decline to remove it. - call confirm('This file is not in your local directory: '.filename."\n". - \ 'It will not be deleted.' , '&OK', 1) - - else - let ch = confirm('Really delete '.filename.' ?', "&Yes\n&No", 2) - if ch == 1 - call delete(s:macrodirpath.filename) - endif - call RedrawMacro() - endif -endfunction - -" }}} -" EditMacro: edits macro file {{{ -function! EditMacro(...) - if a:0 > 0 - let filename = a:1 - else - let filename = s:ChooseMacro('Choose a macro file for insertion:') - endif - - if filereadable(s:macrodirpath.filename) - " If file exists in local directory open it. - exec 'split '.Tex_EscapeSpaces(s:macrodirpath.filename) - else - " But if file doesn't exist in local dir it probably is in user - " restricted area. Instead opening try to copy it to local dir. - " Pity VimL doesn't have mkdir() function :) - let ch = confirm("You are trying to edit file which is probably read-only.\n". - \ "It will be copied to your local LaTeX-Suite macros directory\n". - \ "and you will be operating on local copy with suffix -local.\n". - \ "It will succeed only if ftplugin/latex-suite/macros dir exists.\n". - \ "Do you agree?", "&Yes\n&No", 1) - if ch == 1 - " But there is possibility we already created local modification. - " Check it and offer opening this file. - if filereadable(s:macrodirpath.filename.'-local') - let ch = confirm('Local version of '.filename." already exists.\n". - \ 'Do you want to open it or overwrite with original version?', - \ "&Open\nOver&write\n&Cancel", 1) - if ch == 1 - exec 'split '.Tex_EscapeSpaces(s:macrodirpath.filename.'-local') - elseif ch == 2 - new - exe '0read '.Tex_FindInRtp(filename, 'macros') - " This is possible macro was edited before, wipe it out. - if bufexists(s:macrodirpath.filename.'-local') - exe 'bwipe '.s:macrodirpath.filename.'-local' - endif - exe 'write! '.s:macrodirpath.filename.'-local' - else - return - endif - else - " If file doesn't exist, open new file, read in system macro and - " save it in local macro dir with suffix -local - new - exe '0read '.Tex_FindInRtp(filename, 'macros') - exe 'write '.s:macrodirpath.filename.'-local' - endif - endif - - endif - setlocal filetype=tex -endfunction - -" }}} -" ReadMacro: reads in a macro from a macro file. {{{ -" allowing for placement via placeholders. -function! ReadMacro(...) - - if a:0 > 0 - let filename = a:1 - else - let filelist = Tex_FindInRtp('', 'macros') - let filename = - \ Tex_ChooseFromPrompt("Choose a macro file:\n" . - \ Tex_CreatePrompt(filelist, 2, ',') . - \ "\nEnter number or name of file :", - \ filelist, ',') - endif - - let fname = Tex_FindInRtp(filename, 'macros', ':p') - - let markerString = '<---- Latex Suite End Macro ---->' - let _a = @a - silent! call append(line('.'), markerString) - silent! exec "read ".fname - silent! exec "normal! V/^".markerString."$/-1\\"ax" - " This is kind of tricky: At this stage, we are one line after the one we - " started from with the marker text on it. We need to - " 1. remove the marker and the line. - " 2. get focus to the previous line. - " 3. not remove anything from the previous line. - silent! exec "normal! $v0k$\"_x" - - call Tex_CleanSearchHistory() - - let @a = substitute(@a, '['."\n\r\t ".']*$', '', '') - let textWithMovement = IMAP_PutTextWithMovement(@a) - let @a = _a - - return textWithMovement - -endfunction - -" }}} -" commands for macros {{{ -com! -nargs=? TMacroNew :call NewMacro() - -" This macros had to have 2 versions: -if v:version >= 602 - com! -complete=custom,Tex_CompleteMacroName -nargs=? TMacro - \ :let s:retVal = ReadMacro() normal! i=s:retVal - com! -complete=custom,Tex_CompleteMacroName -nargs=? TMacroEdit - \ :call EditMacro() - com! -complete=custom,Tex_CompleteMacroName -nargs=? TMacroDelete - \ :call DeleteMacro() - - " Tex_CompleteMacroName: for completing names in TMacro... commands {{{ - " Description: get list of macro names with Tex_FindInRtp(), remove full path - " and return list of names separated with newlines. - " - function! Tex_CompleteMacroName(A,P,L) - " Get name of macros from all runtimepath directories - let macronames = Tex_FindInRtp('', 'macros') - " Separate names with \n not , - let macronames = substitute(macronames,',','\n','g') - return macronames - endfunction - - " }}} - -else - com! -nargs=? TMacro - \ :let s:retVal = ReadMacro() normal! i=s:retVal - com! -nargs=? TMacroEdit :call EditMacro() - com! -nargs=? TMacroDelete :call DeleteMacro() - -endif - -" }}} - -" vim:fdm=marker:ff=unix:noet:ts=4:sw=4 diff --git a/ftplugin/latex-suite/diacritics.vim b/ftplugin/latex-suite/diacritics.vim deleted file mode 100644 index 616d30ab..00000000 --- a/ftplugin/latex-suite/diacritics.vim +++ /dev/null @@ -1,124 +0,0 @@ -"============================================================================= -" File: diacritics.vim -" Author: Lubomir Host -" Created: Tue Apr 23 07:00 PM 2002 PST -" -" Description: shortcuts for all diacritics. -"============================================================================= - -if !g:Tex_Diacritics - finish -endif - -" \'{a} {{{ -call IMAP ('=a', "\\\'{a}", 'tex') -call IMAP ('=b', "\\'{b}", 'tex') -call IMAP ('=c', "\\'{c}", 'tex') -call IMAP ('=d', "\\'{d}", 'tex') -call IMAP ('=e', "\\'{e}", 'tex') -call IMAP ('=f', "\\'{f}", 'tex') -call IMAP ('=g', "\\'{g}", 'tex') -call IMAP ('=h', "\\'{h}", 'tex') -call IMAP ('=i', "\\'{\i}", 'tex') -call IMAP ('=j', "\\'{j}", 'tex') -call IMAP ('=k', "\\'{k}", 'tex') -call IMAP ('=l', "\\'{l}", 'tex') -call IMAP ('=m', "\\'{m}", 'tex') -call IMAP ('=n', "\\'{n}", 'tex') -call IMAP ('=o', "\\'{o}", 'tex') -call IMAP ('=p', "\\'{p}", 'tex') -call IMAP ('=q', "\\'{q}", 'tex') -call IMAP ('=r', "\\'{r}", 'tex') -call IMAP ('=s', "\\'{s}", 'tex') -call IMAP ('=t', "\\'{t}", 'tex') -call IMAP ('=u', "\\'{u}", 'tex') -call IMAP ('=v', "\\'{v}", 'tex') -call IMAP ('=w', "\\'{w}", 'tex') -call IMAP ('=x', "\\'{x}", 'tex') -call IMAP ('=y', "\\'{y}", 'tex') -call IMAP ('=z', "\\'{z}", 'tex') -call IMAP ('=A', "\\'{A}", 'tex') -call IMAP ('=B', "\\'{B}", 'tex') -call IMAP ('=C', "\\'{C}", 'tex') -call IMAP ('=D', "\\'{D}", 'tex') -call IMAP ('=E', "\\'{E}", 'tex') -call IMAP ('=F', "\\'{F}", 'tex') -call IMAP ('=G', "\\'{G}", 'tex') -call IMAP ('=H', "\\'{H}", 'tex') -call IMAP ('=I', "\\'{\I}", 'tex') -call IMAP ('=J', "\\'{J}", 'tex') -call IMAP ('=K', "\\'{K}", 'tex') -call IMAP ('=L', "\\'{L}", 'tex') -call IMAP ('=M', "\\'{M}", 'tex') -call IMAP ('=N', "\\'{N}", 'tex') -call IMAP ('=O', "\\'{O}", 'tex') -call IMAP ('=P', "\\'{P}", 'tex') -call IMAP ('=Q', "\\'{Q}", 'tex') -call IMAP ('=R', "\\'{R}", 'tex') -call IMAP ('=S', "\\'{S}", 'tex') -call IMAP ('=T', "\\'{T}", 'tex') -call IMAP ('=U', "\\'{U}", 'tex') -call IMAP ('=V', "\\'{V}", 'tex') -call IMAP ('=W', "\\'{W}", 'tex') -call IMAP ('=X', "\\'{X}", 'tex') -call IMAP ('=Y', "\\'{Y}", 'tex') -call IMAP ('=Z', "\\'{Z}", 'tex') -" }}} -" \v{a} {{{ -call IMAP ('+a', "\\v{a}", 'tex') -call IMAP ('+b', "\\v{b}", 'tex') -call IMAP ('+c', "\\v{c}", 'tex') -call IMAP ('+d', "\\v{d}", 'tex') -call IMAP ('+e', "\\v{e}", 'tex') -call IMAP ('+f', "\\v{f}", 'tex') -call IMAP ('+g', "\\v{g}", 'tex') -call IMAP ('+h', "\\v{h}", 'tex') -call IMAP ('+i', "\\v{\i}", 'tex') -call IMAP ('+j', "\\v{j}", 'tex') -call IMAP ('+k', "\\v{k}", 'tex') -call IMAP ('+l', "\\q l", 'tex') -call IMAP ('+m', "\\v{m}", 'tex') -call IMAP ('+n', "\\v{n}", 'tex') -call IMAP ('+o', "\\v{o}", 'tex') -call IMAP ('+p', "\\v{p}", 'tex') -call IMAP ('+q', "\\v{q}", 'tex') -call IMAP ('+r', "\\v{r}", 'tex') -call IMAP ('+s', "\\v{s}", 'tex') -call IMAP ('+t', "\\q t", 'tex') -call IMAP ('+u', "\\v{u}", 'tex') -call IMAP ('+v', "\\v{v}", 'tex') -call IMAP ('+w', "\\v{w}", 'tex') -call IMAP ('+x', "\\v{x}", 'tex') -call IMAP ('+y', "\\v{y}", 'tex') -call IMAP ('+z', "\\v{z}", 'tex') -call IMAP ('+A', "\\v{A}", 'tex') -call IMAP ('+B', "\\v{B}", 'tex') -call IMAP ('+C', "\\v{C}", 'tex') -call IMAP ('+D', "\\v{D}", 'tex') -call IMAP ('+E', "\\v{E}", 'tex') -call IMAP ('+F', "\\v{F}", 'tex') -call IMAP ('+G', "\\v{G}", 'tex') -call IMAP ('+H', "\\v{H}", 'tex') -call IMAP ('+I', "\\v{\I}", 'tex') -call IMAP ('+J', "\\v{J}", 'tex') -call IMAP ('+K', "\\v{K}", 'tex') -call IMAP ('+L', "\\v{L}", 'tex') -call IMAP ('+M', "\\v{M}", 'tex') -call IMAP ('+N', "\\v{N}", 'tex') -call IMAP ('+O', "\\v{O}", 'tex') -call IMAP ('+P', "\\v{P}", 'tex') -call IMAP ('+Q', "\\v{Q}", 'tex') -call IMAP ('+R', "\\v{R}", 'tex') -call IMAP ('+S', "\\v{S}", 'tex') -call IMAP ('+T', "\\v{T}", 'tex') -call IMAP ('+U', "\\v{U}", 'tex') -call IMAP ('+V', "\\v{V}", 'tex') -call IMAP ('+W', "\\v{W}", 'tex') -call IMAP ('+X', "\\v{X}", 'tex') -call IMAP ('+Y', "\\v{Y}", 'tex') -call IMAP ('+Z', "\\v{Z}", 'tex') -" }}} -call IMAP ('+}', "\\\"{a}", 'tex') -call IMAP ('+:', "\\^{o}", 'tex') - -" vim:fdm=marker:ff=unix:noet:ts=4:sw=4 diff --git a/ftplugin/latex-suite/elementmacros.vim b/ftplugin/latex-suite/elementmacros.vim deleted file mode 100644 index 132291a7..00000000 --- a/ftplugin/latex-suite/elementmacros.vim +++ /dev/null @@ -1,330 +0,0 @@ -"============================================================================= -" File: elementmacros.vim -" Author: Mikolaj Machowski -" Created: Tue Apr 23 06:00 PM 2002 PST -" -" Description: macros for dimensions/fonts/counters. -" and various common commands such ref/label/footnote. -"============================================================================= - -nmap