Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim function to insert a Python import if it hasn't been imported yet

I currently have a Vim function that will wrap selected text within a time.time() block so that I can quickly time things.

I would like for the function to also go to the top of the file, check if import time exists or not, and insert import time only if it doesn't exist already.

Is there any way to check if text exists or not in Vim?

like image 587
J-Win Avatar asked Jan 02 '26 02:01

J-Win


1 Answers

This is what I currently have. It works, but please do post your own solution if you have something better!

Also, note that the line that has the ^M is formed by pressing Ctrl-V and then the Enter button in insert mode (Stack Overflow doesn't copy it over 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>)
like image 111
J-Win Avatar answered Jan 03 '26 16:01

J-Win



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!