Files
overleaf-cep/services/web/shared/bibtex/bibtex-purify.mts
T
Eric Mc Sween 7d3d60f2ba Merge pull request #36920 from overleaf/em-shared-frontend-backend
Move shared bibtex model classes to services/web/shared

GitOrigin-RevId: ef768d4f7bcf7b9c4b41844450b0256ecb46fdae
2026-09-17 12:08:21 +00:00

50 lines
1.4 KiB
TypeScript

/**
* Implements the BibTeX purify$ function for special characters
*
* Special characters are first level groupings of curly braces that start with
* a backslash (e.g. "This is a special character: {\textbf{hello}}"). Inside
* special characters, LaTeX commands are removed.
*
* For more details, see Tame the BeaST, section 10
* (https://tug.ctan.org/info/bibtex/tamethebeast/ttb_en.pdf)
*/
export function purifySpecialChars(s: string) {
let result = ''
let currSpecialChar: string | null = null
let openBraces = 0
for (let i = 0; i < s.length; i++) {
const c = s[i]
if (c === '{') {
openBraces += 1
} else if (c === '}') {
openBraces -= 1
} else if (c === '\\' && openBraces === 1) {
// Open a special character
currSpecialChar = ''
}
if (currSpecialChar != null && openBraces === 0) {
// We just closed a special char: remove all LaTeX command and add to the
// result
result += currSpecialChar.replaceAll(/\\([A-Za-z]+|[^A-Za-z])\s*/g, '')
currSpecialChar = null
}
// Accumulate the character either in the current special character or in
// the final result
if (currSpecialChar != null) {
currSpecialChar += c
} else {
result += c
}
}
// If the string is malformed, just append the unprocessed special character
// as-is
if (currSpecialChar != null) {
result += currSpecialChar
}
return result
}