thephpleague / commonmark

Highly-extensible PHP Markdown parser which fully supports the CommonMark and GFM specs.
https://commonmark.thephpleague.com
BSD 3-Clause "New" or "Revised" License
2.75k stars 194 forks source link

add getLineOffset() to MarkdownInput #1039

Open bwl21 opened 3 months ago

bwl21 commented 3 months ago

Description

I have a markdown File with frontMatter, so I use the frontmatterextension to get the source witthout frontmatter. But then the line numbers in the nodes no longer match with the original source file.

In order to fix this, I should have access to the lineOffset which gives the first line of the source without frontmatter.

By this I could implement a proper reporting.

As of now I work around this. But it would be simpler if MarkdownInput had a getter for $lineOffset

maybe it would even be possible that the frontmatter is represented in the AST.

Example

    public function load(string $markdown): self {
        $frontMatterAndMarkdown = $this->parseFrontMatter($markdown);
        $this->sourceText = new SourceText($frontMatterAndMarkdown->markdown);
        $this->documentAst = $this->markdownParser->parse($frontMatterAndMarkdown->markdown);
        $this->lineOffset = $this->getLineOffset($markdown, $frontMatterAndMarkdown->markdown);
        return $this;
    }

    private function getLineOffset($markdownWithFrontmatter, $markdown) {
        $startpos = strpos($markdownWithFrontmatter, $markdown);
        return substr_count($markdownWithFrontmatter, "\n", 0, $startpos);
    }

would be

    public function load(string $markdown): self {
        $frontMatterAndMarkdown = $this->parseFrontMatter($markdown);
        $this->sourceText = new SourceText($frontMatterAndMarkdown->markdown);
        $this->documentAst = $this->markdownParser->parse($frontMatterAndMarkdown->markdown);
        $this->lineOffset = $frontMatterAndMarkdown->getLineOffset(); // <---
        return $this;
    }

Did this project help you today? Did it make you happy in any way?

This project is great, has a clear architecture and no surprises. Thanks so much.