代码:
// 数组可能越界, 可以自己往后面添加序号
module.exports = init
let quickAddApi
let list = ["📑 添加排序", "🆑 清除排序"]
let type = ["sort", "clear"]
let level
let count = [0, 0, 0, 0, 0, 0]
let select = 1 // 判断是否划选
let ht = [
["一、", "二、", "三、", "四、", "五、", "六、", "七、", "八、", "九、", "十、"],
["(一)", "(二)", "(三)", "(四)", "(五)", "(六)", "(七)", "(八)", "(九)", "(十)"],
["1.", "2.", "3.", "4.", "5.", "6.", "7.", "8.", "9.", "10."],
["1)", "2)", "3)", "4)", "5)", "6)", "7)", "8)", "9)", "10)",],
["A.", "B.", "C.", "D.", "E.", "F.", "G.", "H.", "I.", "J."],
["a.", "b.", "c.", "d.", "e.", "f.", "g.", "h.", "i.", "j."]
]
async function init(params) {
({ quickAddApi } = params)
const q = await quickAddApi.suggester(list, type);
switch (q) {
case "sort":
return await sort()
break
case "clear":
return await clear()
break
}
}
async function sort() {
level = -1
const activeLeaf = app.workspace.activeLeaf
let selection = activeLeaf.view.editor.getSelection()
if (selection == "") {
selection = app.workspace.activeLeaf.view.editor.view.data
select = 0
}
const tArr = selection.split("\n")
let result = ""
for (let index = 0; index < tArr.length; index++) {
const line = tArr[index];
let h = line.split(" ")[0] + " "
for (let hl = 0; hl < 6; hl++) {
if (h == "#".times(hl + 1) + " ") {
if (level > hl) count[level] = 0
level = hl
tArr[index] = tArr[index].replace(h, h + ht[level][count[level]++])
}
}
result += tArr[index]
if (index < tArr.length - 1) result += "\n"
}
if (select) return result
app.workspace.activeLeaf.view.editor.cm.setValue(result)
}
async function clear() {
const activeLeaf = app.workspace.activeLeaf
let selection = activeLeaf.view.editor.getSelection()
if (selection == "") {
selection = app.workspace.activeLeaf.view.editor.view.data
select = 0
}
for (let i = 0; i < ht.length; i++) {
for (let j = 0; j < ht[i].length; j++) {
selection = selection.replace(new RegExp("#".times(i + 1) + " " + ht[i][j], "gm"), "#".times(i + 1) + " ");
}
}
if (select) return selection
app.workspace.activeLeaf.view.editor.cm.setValue(selection)
}
String.prototype.times = function (n) {
return Array.prototype.join.call({ length: n + 1 }, this);
};
使用教程:
- 将js代码放到你的
templater
脚本目录 - 新增一个宏
- 新增一个
capture
如图设置 she zhi
{{MACRO:文章::titleSort:init}}
注意替换 宏, 和 js 文件的名字
- 享受吧