I am facing the following problem: a function, triggered by a :nnoremap inserts a few lines into a buffer. Since I have folding enabled with foldexpr=... and the inserted text contains this expression, the inserted text is folded.

I could stop this unwanted behaviour by setting nofoldenable. Yet, if I do that, the already existing folds are opened. This is also not what I want. The existing folds should stay as the are, opened or closed.

So, is it possible to tell vim somehow that the inserted text is to be inserted without trying to fold it?

  • What happens if, after insertion, you add a :silent! :normal! zO inside your function?
    – VanLaser
    Commented Aug 16, 2015 at 17:14
  • @VanLaser zO and friends work recursively on folds under the cursor, but inserting text in a function doesn't necessarily happen at the cursor position (append(), for instance, appends by line number and doesn't move the cursor; neither does it set the '[,'] marks).
    – jjaderberg
    Commented Aug 21, 2015 at 8:18
  • @Rene I think my answer should be a working solution. Am I wrong? Commented Aug 23, 2015 at 21:35
  • @KarlYngveLervåg I am currently in a foreign country and don't have my development computer with me, so that I cannot check if it works for me. Please allow me another week until I'll come back to your answer. Sorry for the delay. Commented Aug 24, 2015 at 11:21

1 Answer 1


You can temporarily disable the foldexpr by setting foldmethod to manual during the execution of the function. You could do this in your function like this:

function! MyMappedFunction(...)
  let l:foldmethod=&foldmethod 
  setlocal foldmethod=manual

  " ... function content ...

  let foldmethod=l:foldmethod
end function

Note that the old foldmethod is saved in order to restore it after the function is finished.

  • 1
    I would also save the configured foldmethod before overriding it, this way you could restore the previous configuration automatically.
    – nobe4
    Commented Aug 18, 2015 at 15:20
  • Because of other problems with updating folds and because of a bug(?) in Vim for insert mode+expression folding I always do this when entering insert mode and restore when leaving insert mode or leaving the window, see vi.stackexchange.com/questions/3128/…
    – jjaderberg
    Commented Aug 21, 2015 at 8:23
  • Thanks @Nobe4, I noticed your comment but I forgot to update afterwords. Commented Aug 23, 2015 at 21:35

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.