I am attempting custom fold logic as my first VimScript.

What works for me: USING VERY MAGIC (\v) and explicit CASE SENSITIVE (\C), find python comments in foo.py that begin with hash, then Roman Numeral, a period, and finally .*$


I want to apply this pattern to tell Vim when to start a fold in my Python scripts. The same pattern that works in foo.py now stops working once I pass it to a function. I assign the pattern to a variable in match() in python.vim:

function! PythonFolds()
  let thisline = getline(v:lnum)

  let rom_num = "\v\C^#(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})\.\s.*$.@<="
  if match(thisline, rom_num) >= 0
    return ">1"
    return "=" 

setlocal foldmethod=expr
setlocal foldexpr=PythonFolds()
setlocal foldcolumn=4

Basically when the above code is applied to a python.vim preference file, the folds are not applied. I have successfully tested simpler regex, which makes me believe the problem can be isolated as something I don't understand with regex/VimScript:

 if match(thisline, "^#") >= 0      " folds work as intended
   return ">1"

Additionally, the tutorials below suggest that \v and \C are both passable in VimScript.

I am running Vim8 on Ubuntu 18.04.

  • Where did you put the file? Is folding enabled (zi)? Did you check the value of of the options you set (setlocal foldmethod? foldexpr? foldcolumn?)
    – D. Ben Knoble
    Mar 21, 2019 at 0:52
  • 1
    Have you tried using single quotes around your pattern?
    – D. Ben Knoble
    Mar 21, 2019 at 0:53
  • 1
    If you use double quotes, you need to double the backslashes, so use single quotes. See :h expr-quote Mar 21, 2019 at 6:49
  • Single quotes worked, which means Vimscript indeed accepts \v and \C in pattern definitions. If there is a way to select comment as answer, please let me know. Mar 22, 2019 at 18:40


Your Answer

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

Browse other questions tagged or ask your own question.