Started editing a JavaScript file, did :set filetype=javascript (correct syntax highlighting kicked in), then set foldmethod=syntax, and naively expected that folding should automatically work, but that's not the case. What am I missing?

:help fold-syntax states:

SYNTAX fold-syntax

A fold is defined by syntax items that have the "fold" argument. |:syn-fold|

The fold level is defined by nesting folds. The nesting of folds is limited with 'foldnestmax'.

Be careful to specify proper syntax syncing. If this is not done right, folds may differ from the displayed highlighting. This is especially relevant when using patterns that match more than one line. In case of doubt, try using brute-force syncing: :syn sync fromstart

Found the files affecting the rendering of the buffer using :scriptnames (with the help of this thread and this) - the list has 98 files, including at line 75: vim-8.2.3451/share/vim/vim82/syntax/javascript.vim (linked to the Vim source code entry as it is an exact match).

The only place there is a fold word is in this block, but too much of a novice to make sense of :help syn-fold...

if exists("javaScript_fold")
    syn match   javaScriptFunction  "\<function\>"
    syn region  javaScriptFunctionFold  start="\<function\>.*[^};]$" end="^\z1}.*$" transparent fold keepend

    syn sync match javaScriptSync   grouphere javaScriptFunctionFold "\<function\>"
    syn sync match javaScriptSync   grouphere NONE "^}"

    setlocal foldmethod=syntax
    setlocal foldtext=getline(v:foldstart)
    syn keyword javaScriptFunction  function
    syn match   javaScriptBraces       "[{}\[\]]"
    syn match   javaScriptParens       "[()]"
  • 2
    You need to set the variable javaScript_fold before you edit a JavaScript file: :let g:javaScript_fold = 1
    – Heptite
    Mar 3, 2022 at 23:31
  • 1
    Try adding let g:javaScript_fold = 1 to your vimrc file? Let me know if that works for you, I can turn it into an answer then... (Though I see Heptite got there first, so I'll leave it to them to post it as an answer.)
    – filbranden
    Mar 3, 2022 at 23:40
  • Yep, that was it. Feel like an idiot, but at least it works..:) Thank you to both of you! (.. and if an answer is posted, will accept it right away.)
    – toraritte
    Mar 4, 2022 at 1:49


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.