// Copyright (c) 2009-2022 The MathJax Consortium
// SPDX-License-Identifier: Apache-2.0
// Go translation of base/BaseMethods.Entry (MathJax 3.2.2).

package tex

import (
	

	
)

// Entry scans the second cases column as text before ordinary TeX tokenization.
// In particular, percent is literal here, and a row command ends the scan even
// inside braces. close records the first complete group for the \text exception.
func matrixCasesTextEnd( string,  int) (,  int,  error) {
	,  := 0, -1
	 := 
	for  < len() {
		switch [] {
		case '{':
			++
			++
		case '}':
			if  == 0 {
				return , , nil
			}
			--
			if  == 0 &&  < 0 {
				 =  - 
			}
			++
		case '&':
			if  == 0 {
				return , , texError("ExtraAlignTab", "Extra alignment tab in \\cases text")
			}
			++
		case '\\':
			 := [:]
			if strings.HasPrefix(, `\\`) || strings.HasPrefix(, `\cr`) && len() > 3 && !isASCIILetter(rune([3])) {
				return , , nil
			}
			 += 2
		default:
			++
		}
	}
	return len(), , nil
}

func ( *parser) ( string,  byte) (*mml.Node, error) {
	, ,  := matrixCasesTextEnd(, 0)
	if  != nil {
		return nil, 
	}
	 := strings.TrimLeftFunc(, internalTextSpace)
	if strings.HasPrefix(, `\text`) && len() > 5 && !isASCIILetter(rune([5])) &&
		 == len(strings.TrimRightFunc(, internalTextSpace))-1 {
		// Preserve the source's backwards compatibility: a complete \text
		// cell is parsed normally, without the automatic level-zero mstyle.
		return .parseMatrixCell(, )
	}
	 := strings.TrimFunc(, internalTextSpace)
	if strings.HasSuffix(, `\`) && strings.HasSuffix(, " ") {
		 += " " // ParseUtil.trimSpaces preserves a trailing control-space.
	}
	 := .matrixCellParser("")
	,  := .internalMath(, "", true)
	if  != nil {
		return nil, 
	}
	return matrixCellContent(), nil
}

// BaseMethods.Entry reads a cases text column before returning to Parse. The
// raw scanner intentionally recognizes only the source's literal CR spellings.
func ( *parser) () ([]*mml.Node, error) {
	// The captured environment has an implicit end token. The scanner's
	// trailing non-letter keeps a final literal \cr recognizable as in the
	// original uncut program, without placing that sentinel in math input.
	, ,  := matrixCasesTextEnd(.source+"}", .pos)
	if  != nil {
		return nil, 
	}
	if  > len(.source) {
		 = len(.source)
	}
	 := .source[.pos:]
	 := strings.TrimLeftFunc(, internalTextSpace)
	if strings.HasPrefix(, `\text`) && len() > 5 && !isASCIILetter(rune([5])) &&
		 == len(strings.TrimRightFunc(, internalTextSpace))-1 {
		return nil, nil
	}
	.pos = 
	 := strings.TrimFunc(, internalTextSpace)
	if strings.HasSuffix(, `\`) && strings.HasSuffix(, " ") {
		 += " "
	}
	return .internalMath(, "", true)
}