package lexers

import (
	

	.  // nolint
)

// Markdown lexer with YAML frontmatter and HTML comment support.
var Markdown = Register(&markdownLexer{Lexer: MustNewLexer(
	&Config{
		Name:      "markdown",
		Aliases:   []string{"md", "mkd"},
		Filenames: []string{"*.md", "*.mkd", "*.markdown"},
		MimeTypes: []string{"text/x-markdown"},
	},
	markdownRules,
)})

// markdownLexer wraps the base Markdown lexer to highlight top-of-file YAML frontmatter.
type markdownLexer struct {
	Lexer
}

// Lexes Markdown, highlighting a leading YAML frontmatter block before delegating to Markdown rules.
func ( *markdownLexer) ( *TokeniseOptions,  string) (Iterator, error) {
	, ,  := splitFrontmatter()
	if ! {
		return .Lexer.Tokenise(, )
	}

	 := Get("YAML")
	if  == nil {
		return .Lexer.Tokenise(, )
	}

	,  := .Tokenise(, )
	if  != nil {
		return nil, 
	}
	,  := .Lexer.Tokenise(, )
	if  != nil {
		return nil, 
	}
	return Concaterator(, ), nil
}

// Extracts a leading YAML frontmatter block if the document starts with one.
func splitFrontmatter( string) ( string,  string,  bool) {
	if !strings.HasPrefix(, "---\n") && !strings.HasPrefix(, "---\r\n") {
		return "", , false
	}

	 := strings.IndexByte(, '\n')
	if  < 0 {
		return "", , false
	}
	if strings.TrimSuffix([:], "\r") != "---" {
		return "", , false
	}

	for  :=  + 1;  < len(); {
		 := strings.IndexByte([:], '\n')
		if  < 0 {
			break
		}
		 =  + 
		 := strings.TrimSuffix([:], "\r")
		if  == "---" {
			return [:+1], [+1:], true
		}
		 =  + 1
	}
	return "", , false
}

func markdownRules() Rules {
	return Rules{
		"root": {
			{`<!--[\w\W]*?-->`, CommentMultiline, nil},
			{`^(#[^#].+\n)`, ByGroups(GenericHeading), nil},
			{`^(#{2,6}.+\n)`, ByGroups(GenericSubheading), nil},
			{`^(\s*)([*-] )(\[[ xX]\])( .+\n)`, ByGroups(Text, Keyword, Keyword, UsingSelf("inline")), nil},
			{`^(\s*)([*-])(\s)(.+\n)`, ByGroups(Text, Keyword, Text, UsingSelf("inline")), nil},
			{`^(\s*)([0-9]+\.)( .+\n)`, ByGroups(Text, Keyword, UsingSelf("inline")), nil},
			{`^(\s*>\s)(.+\n)`, ByGroups(Keyword, GenericEmph), nil},
			{"^(```\\n)([\\w\\W]*?)(^```$)", ByGroups(String, Text, String), nil},
			{
				"^(```)(\\w+)(\\n)([\\w\\W]*?)(^```$)",
				UsingByGroup(2, 4, String, String, String, Text, String),
				nil,
			},
			Include("inline"),
		},
		"inline": {
			{`<!--[\w\W]*?-->`, CommentMultiline, nil},
			{`\\.`, Text, nil},
			{`(\s)(\*|_)((?:(?!\2).)*)(\2)((?=\W|\n))`, ByGroups(Text, GenericEmph, GenericEmph, GenericEmph, Text), nil},
			{`(\s)((\*\*|__).*?)\3((?=\W|\n))`, ByGroups(Text, GenericStrong, GenericStrong, Text), nil},
			{`(\s)(~~[^~]+~~)((?=\W|\n))`, ByGroups(Text, GenericDeleted, Text), nil},
			{"`[^`]+`", LiteralStringBacktick, nil},
			{`[@#][\w/:]+`, NameEntity, nil},
			{`(!?\[)([^]]+)(\])(\()([^)]+)(\))`, ByGroups(Text, NameTag, Text, Text, NameAttribute, Text), nil},
			{`.|\n`, Text, nil},
		},
	}
}