recital / core / src / pipeline / 04-tokens / plugins / softlines.ts
softlines.ts
Raw
/**
 * Copyright (c) 2022 Amorphous
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

import eol from 'eol'
import { StringParserPlugin } from '../../../types'

const SOFTLINE_PLACEHOLDER = '%LINE%'

export const preprocessSoftLines: StringParserPlugin = (raw: string): string => {
	const lfRaw = eol.lf(raw)
	return lfRaw.replace(/(?<!\\)\\\n/gm, SOFTLINE_PLACEHOLDER)
}

export const parseSoftLines: StringParserPlugin = (raw: string): string => {
	const lfRaw = eol.lf(raw)
	const softlineRegex = new RegExp(SOFTLINE_PLACEHOLDER, 'gm')
	const escapeRegex = /\\\\\n/gm
	const escaped = lfRaw.replace(escapeRegex, '\\\n')
	return escaped.replace(softlineRegex, '\n')
}