Instead of using the
zf Normal mode command, it's easier if you use the
:fold Ex command, which takes a range and fits naturally in a function. So you can easily fold the block starting on the first line that has
Copyright and going up to the next line with
CONNECTION using the following:
I added a
silent! there so it fails silently if those strings are not found.
You can also add a
/^$ to this function if you like. (You don't really need
/ works as an Ex command, only caveat is that it goes to the first character of the line, which should be totally fine in this particular case.)
Regarding file type matching, the
*.h header files are not really mapped to a
h FileType... Instead, they can map to either C, C++ or Objective-C, depending on some auto-detecting code and some global configuration variables.
If Objective-C is not detected (which is done by looking for Objective-C specific keywords such as
@class), then it defaults to C++ (
FileType cpp), but you can control that to have them use the C file type by setting global variable
g:c_syntax_for_h to 1.
As a final polish to your code, it's best practice to always put your
autocmds inside an
augroup, so that if you end up sourcing your vimrc file (or script where you have them defined) again, you won't end up with duplicated
So, putting it all together:
let g:c_syntax_for_h = 1
au FileType c call FoldLicense()
For completeness, if you really wanted to use the
zf Normal mode command to fold this block from a function, you would need something like this instead:
execute "normal! zf/CONNECTION/e\<CR>"
zf command takes a motion as an argument, you would have to use the search right after it. You should add a
/e to move to the last character in the match, otherwise if
CONNECTION is the the first character on the line, the fold would actually end on the line preceding it. You also need to add a
<CR> to have it execute the search to complete the motion, so you need to use
:execute to pass it to
As mentioned above, using
:fold is a much easier and reliable way to accomplish the same.