Vim function to insert Python imports if not already imported

I currently have a Vim function that will wrap the selected text in a block time.time()

so that I can run through time quickly.

I would like the function to hit the top of the file as well, check if it exists or not import time

, and import time

only insert if it doesn't already exist.

Is there a way to check if text exists in Vim?

+3


source to share


1 answer


This is what I have now. It works, but please post your own solution if you have anything better!

Also note that the string with ^M

is formed by a click Ctrl-V

and then a button Enter

in insert mode (Stack Overflow doesn't copy it very well).



" 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>)

      

+3


source







All Articles