Search code examples
regexvim

replace regular expression via vimscript


I want to replace the following occurings:

@todo call customer
@todo-next do foo
@todo-wait customer will call me back

with @done when I am with the curser on the line. E.g:

@todo call customer

shall be then

@done call customer

I got it to replace @todo but for the other two (@todo-next, @todo-wait) I think my regex does not work properly...

Heres what I got, when I run it nothings happens on the lines...:

function! Tdone(  )
    let line=getline('.')
    "let newline = substitute(line, "@todo", "@done", "")
    let newline = substitute(line, "@todo.*? ", "@done", "")
    call setline('.', newline)
    :w
endfunction

Solution

  • Your regexp syntax is wrong; Vim doesn't understand the Perlish .*?; that's .\{-} in Vim. See :help perl-patterns. (Additionally, since you're matching the trailing whitespace, you need to include that in the replacement, too, or use \ze to restrict the match.)

    let newline = substitute(line, "@todo.\{-} ", "@done ", "")
    

    I'd probably be more restrictive in your pattern, to avoid false matches (depends on the exact syntax of your markers, though, so this is just an example):

    let newline = substitute(line, "@todo\%(-\w\+\)* ", "@done ", "")
    

    Finally, there's no need for getline() / setline(); you can do that with :substitute, too. If you keep the function, this doesn't clobber the last search pattern. To clean up the history, :call histdel('search', -1).