2017-07-28 45 views
3

我目前有一个Vim函数,将选定的文本包装在一个time.time()块,以便我可以快速处理事情。Vim函数插入一个Python导入,如果它尚未导入

我希望函数也能够到文件顶部,检查是否存在import time,并且只有在import time不存在时才插入import time

有什么方法可以检查文本是否存在或不在Vim中?

回答

3

这就是我目前所拥有的。它的工作原理,但如果你有更好的东西,请发布你自己的解决方案!

此外,请注意,具有^M的行是通过在插入模式下按下Ctrl-V然后按Enter按钮形成的(Stack Overflow不能很好地复制它)。

" easily wrap the selected text in a time.time() statement for quick timing 
fun! s:PythonTiming(line1, line2) 

    " mark line one && keep track of lines selected 
    execute 'normal!' 'me' 
    let l:numDiff = a:line2 - a:line1 

    " start timing 
    execute 'normal!' 'Ostart = time.time()' 

    " end timing 
    while line('.') < a:line2 + 1 
     execute 'normal!' 'j' 
    endwhile 
    execute 'normal!' 'oend = time.time()' 
    execute 'normal!' 'oprint; print("end - start: "); print(end - start)' 

    " add the `import time` statement if not already imported 
    let match = search('import time', 'nw') 
    if match == 0 
     silent! execute 'normal!' 'gg/import/^M' 
     execute 'normal!' 'oimport time' 
    endif 

    " go back to the initial mark 
    execute 'normal!' '`e' 

endfun 
command! -range Time :call s:PythonTiming(<line1>, <line2>)