Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
quarto-dev
GitHub Repository: quarto-dev/quarto-cli
Path: blob/main/src/core/execute-inline.ts
3557 views
1
/*
2
* execute-inline.ts
3
*
4
* Copyright (C) 2021-2022 Posit Software, PBC
5
*/
6
7
import {
8
asMappedString,
9
mappedConcat,
10
MappedString,
11
mappedSubstring,
12
} from "./lib/mapped-text.ts";
13
14
export function executeInlineCodeHandler(
15
language: string,
16
exec: (expr: string) => string | undefined,
17
) {
18
const exprPattern = new RegExp(
19
"(^|[^`])`{" + language + "}[ \t]([^`]+)`",
20
"g",
21
);
22
return (code: string) => {
23
return code.replaceAll(exprPattern, (match, prefix, expr) => {
24
const result = exec(expr.trim());
25
if (result) {
26
return `${prefix}${result}`;
27
} else {
28
return match;
29
}
30
});
31
};
32
}
33
34
export function executeInlineCodeHandlerMapped(
35
language: string,
36
exec: (expr: string) => string | undefined,
37
) {
38
const exprPattern = new RegExp(
39
"(^|[^`])`{" + language + "}[ \t]([^`]+)`",
40
"g",
41
);
42
return (code: MappedString) => {
43
let matches: RegExpExecArray | null;
44
const result: MappedString[] = [];
45
let prevIndex = 0;
46
while ((matches = exprPattern.exec(code.value))) {
47
// everything before the match
48
result.push(mappedSubstring(code, prevIndex, matches.index));
49
const matchMapped = mappedSubstring(
50
code,
51
matches.index,
52
matches.index + matches[0].length,
53
);
54
// the first capture group is the prefix
55
const prefixMapped = mappedSubstring(
56
code,
57
matches.index,
58
matches.index + matches[1].length,
59
);
60
// the second capture group is the expression
61
const exprStr = matches[2];
62
63
const exprResult = exec(exprStr.trim());
64
if (exprResult) {
65
result.push(prefixMapped);
66
result.push(asMappedString(exprResult));
67
} else {
68
result.push(matchMapped);
69
}
70
71
// const expr = code.slice(matches.index + matches[1].length);
72
// const result = exec(expr.trim());
73
// if (result) {
74
// result.push(prefix);
75
// result.push(result);
76
// } else {
77
// result.push(code.slice(prevIndex, matches.index + matches[0].length));
78
// }
79
prevIndex = matches.index + matches[0].length;
80
}
81
result.push(mappedSubstring(code, prevIndex));
82
return mappedConcat(result);
83
};
84
}
85
86