I have a plugin that does syntax highlighting and folding for a kind of data file. The syntax and folding are both dependent on textual values in specific places (columns) of current line of text.

My plugin works, but is very slow. I'm a novice at vimscript and was hoping someone could point me to a more efficient way of extracting the appropriate textual markers

I've used the :profile tool and found that the following lines can take the majority of the time. (These are all in the function used for folding.)

let line = getline(v:lnum)

let g:previous_mat = g:current_mat
let g:current_mat = str2nr(strpart(line, 67,3))

let g:previous_mf = g:current_mf
let g:current_mf = str2nr(strpart(line, 70, 2))

let g:previous_mt = g:current_mt
let g:current_mt = str2nr(strpart(line, 72, 3))

Now, perhaps this is the best way to do it and folding is just slow because I have large files (several hundred thousand lines is not uncommon). Please advise a vimscript novice.

  • I wonder if the use of global variables is a problem here... Also, I believe you're assuming that the "previous" ones will point at the line above this one, but that's not really the case as you don't really have control over the order in which the lines get processed... I recommend instead finding the previous line (maybe with prevnonblank()?) and splitting it explicitly. – filbranden Jun 3 '20 at 16:55
  • I assumed the file was read in order. Are you suggesting it isn't? The above works, it's just slow. Are global variables inherently slow? – jlconlin Jun 3 '20 at 16:58
  • Well, I can think of at least one corner case, when you scroll the screen up or down Vim might recalculate folds for only part of the buffer, and the "current" variables will be pointing at whatever was calculated last. It might be a rare situation, but I think it might break in at least a few corner cases... – filbranden Jun 3 '20 at 17:02
  • 1
    Globals would be plain wrong if you have more than one file with that foldexpr. – D. Ben Knoble Jun 3 '20 at 21:25
  • @D.BenKnoble Yep, I see what you are saying. When I was trying to put this together several years ago, that was the only way I could get it to work. – jlconlin Jun 3 '20 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.