拓展:F2 重命名三合一 (小标题、嵌入文件、当前文档)
多个链接请单独选择后运行:
QuickAdd Macro代码
/*
* @Author: 熊猫别熬夜
* @Date: 2024-03-27 11:51:21
* @Last Modified by: 熊猫别熬夜
* @Last Modified time: 2024-03-28 22:20:45
*/
const path = require('path');
const quickAddApi = app.plugins.plugins.quickadd.api;
module.exports = async (params) => {
let file = app.workspace.getActiveFile();
if (app.workspace.activeEditor) {
const editor = app.workspace.activeEditor.editor;
// 选择所在的一行
const line = editor.getLine(editor.getCursor().line);
// 获取选中的文本否则自动获取当前行的文本
const selection = editor.getSelection() ? editor.getSelection() : line;
// !如果为标题
const regex = /^(#+)\s(.*)/;
const matches = selection.match(regex);
if (matches) {
// 重命名小标题
app.commands.executeCommandById('editor:rename-heading');
return;
}
// !如果为wiki链接
let selectionEmbed = matchSelectionEmbed(selection);
if (selectionEmbed) {
console.log(selectionEmbed);
const files = app.vault.getFiles();
// Wiki: 获取库所有文件列表
const wikiPath = getFilePath(files, selectionEmbed); // 匹配Wiki链接
console.log(wikiPath);
if (!wikiPath) {
return;
};
let newName = await quickAddApi.inputPrompt(`🗳重命名嵌入${path.extname(wikiPath)}文件`, null, path.basename(wikiPath).replace(path.extname(wikiPath), ""), "");
if (!newName) return;
await app.fileManager.renameFile(app.vault.getAbstractFileByPath(wikiPath), `${path.dirname(wikiPath)}/${newName}${path.extname(wikiPath)}`);
return;
};
}
// !最终重命名文件
let newName = await quickAddApi.inputPrompt('📄重命名当前文档', null, String(file.basename));
if (!newName) return;
await app.fileManager.renameFile(file, `${file.parent.path}/${newName}.${file.extension}`);
return;
};
function matchSelectionEmbed(text) {
const regex = /\[\[?([^\]]*?)(\|.*)?\]\]?\(?([^)\n]*)\)?/;
const matches = text.match(regex);
if (!matches) return;
if (matches[3]) return decodeURIComponent(matches[3]);
if (matches[1]) return decodeURIComponent(matches[1]);
}
function getFilePath(files, baseName) {
let files2 = files.filter(f => path.basename(f.path).replace(".md", "") === path.basename(baseName).replace(".md", ""));
let filePath = files2.map((f) => f.path);
return filePath[0];
}