Skip to content

Commit

Permalink
ts pandoc codegen - pandocNativeStr
Browse files Browse the repository at this point in the history
  • Loading branch information
cscheid committed Mar 28, 2024
1 parent 1604e4f commit 99b80b9
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/core/pandoc/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,25 @@ export function pandocBlock(delimiterCharacter: ":" | "`") {
};
}

export function pandocNativeStr(content: string): PandocNode {
return {
...basePandocNode,
emit: (ls: EitherString[]) => {
const maxBackticks = content.match(/`+/g)?.[0].length || 0;
const backticks = "`".repeat(maxBackticks + 1);
const escapedContent = content
.replaceAll(
'"',
'\\"',
)
.replaceAll("\n", "\\n");
ls.push(
`${backticks}${'Str "'}${escapedContent}${'"'}${backticks}{=pandoc-native}`,
);
},
};
}

export const pandocDiv = pandocBlock(":");
export const pandocCode = pandocBlock("`");
export const pandocFigure = pandocHtmlBlock("figure");
Expand Down
19 changes: 19 additions & 0 deletions tests/unit/pandoc-codegen/native-string.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
* native-string.test.ts
*
* Copyright (C) 2021-2022 Posit Software, PBC
*
*/

import { unitTest } from "../../test.ts";
import { assertEquals } from "testing/asserts.ts";
import { pandocNativeStr } from "../../../src/core/pandoc/codegen.ts";

// deno-lint-ignore require-await
unitTest("native-string - basics", async () => {
assertEquals(pandocNativeStr("hello").mappedString().value, '`Str "hello"`{=pandoc-native}');
assertEquals(pandocNativeStr('"hello"').mappedString().value, '`Str "\\"hello\\""`{=pandoc-native}');
assertEquals(pandocNativeStr('"hel`lo"').mappedString().value, '``Str "\\"hel`lo\\""``{=pandoc-native}');
assertEquals(pandocNativeStr('"hello\nworld"').mappedString().value, '`Str "\\"hello\\nworld\\""`{=pandoc-native}');
assertEquals(pandocNativeStr('"hello\\\'world"').mappedString().value, '`Str "\\"hello\\\'world\\""`{=pandoc-native}');
})

0 comments on commit 99b80b9

Please sign in to comment.