I want to be able to pass a plain regular expression like so

autocmd BufReadPost * call TextEnableCodeSnip('bash', /^hello/, /^world/, 'SpecialComment')

To a function and use it within as a regular expression without having to convert to a string and back. I want it to have the effect of:

vimfunction! TextEnableCodeSnip(filetype,start,end,textSnipHl) abort
  " ...
  execute 'syntax region textSnip'.ft.'
  \ matchgroup='.a:textSnipHl.'
  \ keepend
  \ start=/^hello/ end=/^world/
  \ contains=@'.group

Which modifying the function like so works fine.

I was hoping that changing the line to look like:

  \ start=start end=end

and just using the variables directly as the data type they were passed as would suffice. Unfortunately, this fails with the error:

E15: Invalid expression: "/^hello/, /^world/, 'SpecialComment')"

Which leads me to believe vim doesn't support this. Does it in another way? Or do I have to use an intermediary string?

I am new to Vimscript and couldn't find anyone else trying to do the same.

  • 1
    You need to pass to the function a valid script object (i.e.: number, string, list, dictionary). 'Regular Expression' is not a valid script object. I would use a string instead. Commented Mar 2, 2023 at 3:46

1 Answer 1


I would suggest to use a string for that:

autocmd BufReadPost * call TextEnableCodeSnip('bash', '^hello', '^world", 'SpecialComment')

function! TextEnableCodeSnip(filetype,start,end,textSnipHl) abort
  " ...
  execute 'syntax region textSnip'.g:ft
  \ 'matchgroup='.a:textSnipHl
  \ 'keepend'
  \ 'start=/'.a:start.'/' 'end=/'.a:end.'/'
  \ 'contains=@'.g:group

Remark: the code seems to assume a 'ft' and 'group' global variables to exist.

  • 1
    Ok, thank you for your reply! This is pretty much where I started but I needed to have clarified that there wasn't a way to pass regex directly and you gave me that clarification. Only reason it matters is because my pattern has quotes in it, so I get to deal with escaping those plus a bunch of double-escaping any regex characters (like \s -> \\s, for instance) when using " strings. My pattern uses both single and double quotes so it'll be fun to escape no matter what. I was hoping there was a way to make the patterns more readable without escaping them, but looks like I'm out of luck
    – drcomputer
    Commented Mar 2, 2023 at 4:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.