115 lines
2.8 KiB
JavaScript
115 lines
2.8 KiB
JavaScript
import { visit } from 'unist-util-visit';
|
|
|
|
/**
|
|
* 自定义 remark 插件来处理 citation 标记
|
|
*/
|
|
export const remarkCitation = () => {
|
|
return (tree) => {
|
|
visit(tree, 'text', (node, index, parent) => {
|
|
const citationRegex = /\[CIT:(\d+)]/g;
|
|
const matches = [...node.value.matchAll(citationRegex)];
|
|
|
|
if (matches.length === 0) return;
|
|
|
|
const newChildren = [];
|
|
let lastIndex = 0;
|
|
|
|
matches.forEach((match) => {
|
|
const [fullMatch, num] = match;
|
|
const startIndex = match.index;
|
|
|
|
// 添加匹配前的文本
|
|
if (startIndex > lastIndex) {
|
|
newChildren.push({
|
|
type: 'text',
|
|
value: node.value.slice(lastIndex, startIndex),
|
|
});
|
|
}
|
|
|
|
// 添加citations节点
|
|
newChildren.push({
|
|
type: 'citations',
|
|
data: {
|
|
hName: 'citations',
|
|
hProperties: {
|
|
dataNums: num,
|
|
},
|
|
},
|
|
children: [{ type: 'text', value: num }],
|
|
});
|
|
|
|
lastIndex = startIndex + fullMatch.length;
|
|
});
|
|
|
|
// 添加剩余文本
|
|
if (lastIndex < node.value.length) {
|
|
newChildren.push({
|
|
type: 'text',
|
|
value: node.value.slice(lastIndex),
|
|
});
|
|
}
|
|
|
|
// 替换原节点
|
|
parent.children.splice(index, 1, ...newChildren);
|
|
});
|
|
};
|
|
};
|
|
|
|
/**
|
|
* 自定义 remark 插件来处理 <think> 标签
|
|
* 将 <think>.....</think> 转换为自定义节点
|
|
*/
|
|
export const remarkThink = () => {
|
|
return (tree) => {
|
|
visit(tree, 'text', (node, index, parent) => {
|
|
const thinkRegex = /<think>([\s\S]*?)<\/think>/g;
|
|
const matches = [...node.value.matchAll(thinkRegex)];
|
|
|
|
if (matches.length === 0) return;
|
|
|
|
const newChildren = [];
|
|
let lastIndex = 0;
|
|
|
|
matches.forEach((match) => {
|
|
const [fullMatch, content] = match;
|
|
const startIndex = match.index;
|
|
|
|
// 添加匹配前的文本
|
|
if (startIndex > lastIndex) {
|
|
newChildren.push({
|
|
type: 'text',
|
|
value: node.value.slice(lastIndex, startIndex),
|
|
});
|
|
}
|
|
|
|
// 添加 think 节点
|
|
newChildren.push({
|
|
type: 'thinkBlock',
|
|
data: {
|
|
hName: 'thinkBlock',
|
|
hProperties: {
|
|
content: content,
|
|
},
|
|
},
|
|
children: [{ type: 'text', value: content }],
|
|
});
|
|
|
|
lastIndex = startIndex + fullMatch.length;
|
|
});
|
|
|
|
// 添加剩余文本
|
|
if (lastIndex < node.value.length) {
|
|
newChildren.push({
|
|
type: 'text',
|
|
value: node.value.slice(lastIndex),
|
|
});
|
|
}
|
|
|
|
// 替换原节点
|
|
parent.children.splice(index, 1, ...newChildren);
|
|
});
|
|
};
|
|
};
|
|
|
|
export default remarkCitation;
|