一些需要调整标题级别的场景
- 有些网络来源的内容,标题起始级别是三或四级
- 有时修改笔记内容,删除了某些标题,子标题需要调整
可行的方法:
- 增强编辑插件:有标题级别调整,但时灵时不灵,原因未知
- linter 插件:可修正非连续标题,但杀伤力有点强
- 手动替换字符串:比较麻烦
所以,改了一个 TP 脚本(来源:Obsidian 标题修改全能脚本v2),可以对选中文本或整个文件中的所有标题,调高或调低级别。
<%*
// 设置标题级别 - templater-js
let file = app.workspace.getActiveFile()
if (file) {
let targets = [
'标题升级',
'标题降级',
'删除标题'
]
let target = await tp.system.suggester(targets,targets)
if (!target){ return }
// 定义一个函数,用于降级标题
let modHeaders = (content) => {
return content.replace(/^#{1,6} (.*)$/gm, (match, p1) => {
let hashCount = match.match(/^#+/)[0].length
let newHashCount = 0
if (target=='标题升级'){
newHashCount = Math.max(hashCount - 1, 1)
} else if (target=='标题降级'){
newHashCount = Math.min(hashCount + 1, 6)
}
if (newHashCount==0){
return p1
}
return `${'#'.repeat(newHashCount)} ${p1}`
})
}
let sel = app.workspace.getActiveFileView().editor.getSelection()
if (sel){
let newContent = modHeaders(sel)
await app.workspace.getActiveFileView().editor.replaceSelection(newContent)
}else{
let content = await app.vault.read(file)
let newContent = modHeaders(content)
await app.vault.modify(file, newContent)
}
new Notice(`已${target}`)
}
-%>
将此代码保存为 .md 文件,放到模板文件夹中
TP 脚本的详细使用方法见:【TP脚本】快速复制标题链接和内联代码 - #7,来自 Moy
