When setting folds manually, it would be handy if it were possible to set the commentstring in a context sensitive manner. Consider the case in which the language uses BCPL-style comment markers (i.e., comments begin with // and are terminated by a newline), the first line of the visual block contains a comment, and the last line does not. Currently, if commentstring is set to //%s, redundant // characters will be appended to the first line when zf is used to create a fold.
Is it possible to set commentstring so that the // characters are added only if they do not already appear on the line?
According to
:help fold-create-marker, automatic folding marker insertiondoes not work properly when:
Thus, it is not possible to change the default
zfbehavior by modifying thecommentstringsetting.However, it is possible to create a custom version of the
zfcommand thatwould take into consideration that starting or ending (or both) lines of
a fold could have comments. For example, consider the following mappings, one
for marking a fold by visual selection, another for using with a motion
command.
Both of the mappings follow the same routine. Before adding starting and
ending folding markers, it checks separately whether the first and the last
lines of the block to fold match the
commentstringpattern. For each of thetwo that do match, it inserts the corresponding marker inside the first found
comment, at the very beginning of its text. Otherwise, the marker is
decorated according to the
commentstringtemplate and added at the end ofthe line.
If in the latter case it is preferable to separate the marker on its own line,
one can change the for loop as shown below.
Unlike the previous version of the loop, the order of processing the two
lines is important: The ending marker line should be added first, if
necessary, because inserting a line for the beginning marker would shift the
following lines changing their numbers.