✨ feat(vscode): 代码阅读的解析与模板直译核心
This commit is contained in:
1 parent
af56985d9a
commit
4d34b8c715
24 files changed
+2294
No files matched your search
@@ -0,0 +1,41 @@
|
||||
/** 按 \n 或 \r\n 切行。 */
|
||||
export function splitLines(text: string): string[] {
|
||||
return text.split(/\r?\n/)
|
||||
}
|
||||
|
||||
/** 非空行共同的前导空白(空格 / 制表符按原样比,不换算)。 */
|
||||
export function commonIndent(lines: string[]): string {
|
||||
let common: string | undefined
|
||||
for (const line of lines) {
|
||||
if (!line.trim())
|
||||
continue
|
||||
const indent = line.slice(0, line.length - line.trimStart().length)
|
||||
if (common === undefined) {
|
||||
common = indent
|
||||
continue
|
||||
}
|
||||
let i = 0
|
||||
while (i < common.length && i < indent.length && common[i] === indent[i])
|
||||
i++
|
||||
common = common.slice(0, i)
|
||||
}
|
||||
return common ?? ''
|
||||
}
|
||||
|
||||
/**
|
||||
* 块内改完的文本(webview 里是去掉共同缩进的样子)→ 写回文件的文本:
|
||||
* 每个非空行补回这几行原来的共同缩进,和 BlockView.code 去缩进的做法互逆。
|
||||
* @param originalLines 被替换的那几行原文
|
||||
*/
|
||||
export function reindentBlock(originalLines: string[], text: string): string {
|
||||
const indent = commonIndent(originalLines)
|
||||
return splitLines(text).map(line => line.trim() ? indent + line : line).join('\n')
|
||||
}
|
||||
|
||||
/** 把 source 的 [startLine, endLine] 整行替换成 text(补回缩进),返回新全文;换行符沿用原文。 */
|
||||
export function replaceLines(source: string, startLine: number, endLine: number, text: string): string {
|
||||
const eol = source.includes('\r\n') ? '\r\n' : '\n'
|
||||
const lines = splitLines(source)
|
||||
const replacement = splitLines(reindentBlock(lines.slice(startLine, endLine + 1), text))
|
||||
return [...lines.slice(0, startLine), ...replacement, ...lines.slice(endLine + 1)].join(eol)
|
||||
}
|
||||
Reference in new issue
Block a user