ikatyang / tree-sitter-yaml

YAML grammar for tree-sitter
https://ikatyang.github.io/tree-sitter-yaml/
MIT License
94 stars 38 forks source link

Some comments should not be nested with blocks #56

Open gzagatti opened 9 months ago

gzagatti commented 9 months ago

I have recently ran into an issue when folding YAML in neovim in which all comments following a sequence get folded with the sequence instead of being left alone.

An example might illustrate the point. Given the following YAML document:

Key1:
  - value 1
  - value 2

# This is a comment to Key 2, it should not belong to the mapping above
Key2: "Value"

We can see from TSPlayground that the comment ends up nested inside of the block_mapping.

document [0, 0] - [6, 0]
  block_node [0, 0] - [6, 0]
    block_mapping [0, 0] - [6, 0]
      block_mapping_pair [0, 0] - [4, 62]
        key: flow_node [0, 0] - [0, 4]
          plain_scalar [0, 0] - [0, 4]
            string_scalar [0, 0] - [0, 4]
        value: block_node [1, 2] - [4, 62]
          block_sequence [1, 2] - [4, 62]
            block_sequence_item [1, 2] - [1, 11]
              flow_node [1, 4] - [1, 11]
                plain_scalar [1, 4] - [1, 11]
                  string_scalar [1, 4] - [1, 11]
            block_sequence_item [2, 2] - [2, 11]
              flow_node [2, 4] - [2, 11]
                plain_scalar [2, 4] - [2, 11]
                  string_scalar [2, 4] - [2, 11]
            comment [4, 0] - [4, 62]
      block_mapping_pair [5, 0] - [5, 13]
        key: flow_node [5, 0] - [5, 4]
          plain_scalar [5, 0] - [5, 4]
            string_scalar [5, 0] - [5, 4]
        value: flow_node [5, 6] - [5, 13]
          double_quote_scalar [5, 6] - [5, 13]

So when folded, comment to Key 2 are hidden away.

image

This is particularly annoying since it's common to add comments above the keys in YAML. In fact, this style of comment features throughout the documentation.

Moreover, the documentation says:

Comments are a presentation detail and must not have any effect on the serialization tree or representation graph. In particular, comments are not associated with a particular node. The usual purpose of a comment is to communicate between the human maintainers of a file. A typical example is comments in a configuration file. Comments must not appear inside scalars, but may be interleaved with such scalars inside collections.

Although, this is open to interpretation I think it would be desirable that the grammar takes comment indentation when parsing. This will allow for a more readable document when folded.