// // KatexUtils.swift // iTexSnip // // Created by Navan Chauhan on 10/13/24. // import Foundation func change(_ inputStr: String, oldInst: String, newInst: String, oldSurrL: Character, oldSurrR: Character, newSurrL: String, newSurrR: String) -> String { var result = "" var i = 0 let n = inputStr.count let inputArray = Array(inputStr) // Convert string to array of characters for easier access while i < n { // Get the range for the substring equivalent to oldInst if i + oldInst.count <= n && inputStr[inputStr.index(inputStr.startIndex, offsetBy: i).. 0 { if inputArray[j] == "\\" && !escaped { escaped = true j += 1 continue } if inputArray[j] == oldSurrR && !escaped { count -= 1 if count == 0 { break } } else if inputArray[j] == oldSurrL && !escaped { count += 1 } escaped = false j += 1 } if count == 0 { let innerContent = String(inputArray[(start + 1).. [Int] { var positions: [Int] = [] var searchRange = string.startIndex.. String { let pattern = try! NSRegularExpression(pattern: "\\\\[a-zA-Z]+\\$.*?\\$|\\$.*?\\$", options: []) var newContent = content let matches = pattern.matches(in: content, options: [], range: NSRange(content.startIndex.. String { let positions = findSubstringPositions(inputStr, substring: oldInst + String(oldSurrL)) var result = inputStr for pos in positions.reversed() { let startIndex = result.index(result.startIndex, offsetBy: pos) let substring = String(result[startIndex.. String { var res = formula // Remove mbox surrounding res = changeAll(inputStr: res, oldInst: "\\mbox ", newInst: " ", oldSurrL: "{", oldSurrR: "}", newSurrL: "", newSurrR: "") res = changeAll(inputStr: res, oldInst: "\\mbox", newInst: " ", oldSurrL: "{", oldSurrR: "}", newSurrL: "", newSurrR: "") // Additional processing similar to the Python version... res = res.replacingOccurrences(of: "\\[", with: "") res = res.replacingOccurrences(of: "\\]", with: "") res = res.replacingOccurrences(of: "\\\\[?.!,\'\"](?:\\s|$)", with: "", options: .regularExpression) // Merge consecutive `text` res = rmDollarSurr(content: res) // Remove extra spaces res = res.replacingOccurrences(of: " +", with: " ", options: .regularExpression) return res.trimmingCharacters(in: .whitespacesAndNewlines) }