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