Using Vim, what is the best way to implement PHP code folding that only folds functions blocks?

StackOverflow https://stackoverflow.com/questions/7149063

  •  08-01-2021
  •  | 
  •  

Question

I'm currently using Vim to edit PHP files and would like to implement code folding for functions only. I've tried setting the foldmethod=expr and using a regex with foldexpr in my .vimrc file. The problem is i don't fully understand how foldexpr is using the regex to apply folding to the source code and i can't seem to get it right.

Basically i want all PHP functions (inside classes too) to be folded and that's it. The nearest i've got is:

set foldexpr=getline(v:lnum-1)=~'function'?'>1':'='

but it's not right and i want to see if i can be a little more intelligent with the curly braces.

Any ideas?

Was it helpful?

Solution

IIRC folding do not work with regexes because it will slow vim down. You might get what you want by using foldmethod=indent and set foldnestmax to limit the number of nested folds created.

OTHER TIPS

I achieved what i needed by using the built-in PHP plugin, activated by putting this in my .vimrc file and not using any other folding settings.

let php_folding = 1        "Set PHP folding of classes and functions.
let php_htmlInStrings = 1  "Syntax highlight HTML code inside PHP strings.
let php_sql_query = 1      "Syntax highlight SQL code inside PHP strings.
let php_noShortTags = 1    "Disable PHP short tags.

Check out the phpfolding plugin.

This is much better than the built-in php_folding syntax stuff because it understands phpdoc/doxygen docblocks, folds the code so you can still see the function name (but hides the documentation which precedes it).

Example:

screenshot

It is a bit weird, you need to run :EnablePHPFolds to update stuff, and I get an odd message when I start up Vim (but that might be because I've installed it with Vundle), but it's a thing of beauty!

(Also referenced at https://stackoverflow.com/a/11859632/623519)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top