Quantcast
Channel: 簡睿隨筆
Viewing all articles
Browse latest Browse all 897

Obs127|用Templater Hotkeys簡化Obsidian自動化腳本,詳解4個腳本範例

$
0
0

用Templater Hotkeys來建立Obsidian自動化腳本,比QuickAdd方便許多。步驟如下:

  1. 安裝並啟用Templater外掛
  2. 新增Templater腳本的.md檔
  3. 到Templater選項裡新增Templater Hotkeys,讓腳本檔變成命令
  4. 為腳本命令設置快捷鍵或用Ctrl/Cmd+P執行命令

本次介紹4個範例,並說明如何使用Dataviewjs查詢命令代碼。

[!tip]+ 建議

  1. 所有腳本檔皆以Cmd-開頭,與一般的模板檔區隔
  2. 腳本檔執行發生錯誤時,將之複製成.js檔,刪除開頭的<%*與結尾的%>後,用VS Code檢視

1. 範例1-選取YAML欄位設定

  • 功用:在YAML區插入筆記種類

gh|700

<%*
let list = {
  "Fleeting Note": "fleeting note",
  "Literature Note": "literature note" ,
  "Permanent Note": "permanent note",
  "Structure Note": "structure note",
  "Meeting Note": "meeting note",
  "Daily Note": "daily note"
};
let keys = Object.keys(list);

let key = await tp.system.suggester(keys, keys);
if (!key) return;
let editor = app.workspace.activeLeaf.view.editor;  // 取編輯器物件
let position = editor.getCursor();  // 取游標物件
let text = editor.getLine(position.line);  // 取游標行的內容
if (text.length > 0) text += "\n";
text = text + "type: " + list[key];
editor.setLine(position.line, text);
-%>

2. 範例2-由選單插入Callout區塊

  • 功用:用選單插入Callout區塊

gh|700

<%*
let list = {
  "ℹ info" : "info,資訊",
  "✏ note" : "note,筆記",
  "📒 summary" : "summary,彙總",
  "🔥 tip" : "tip,技巧",
  "☑ check" : "check,查核",
  "❔Help" : "help,說明",
  "⚠ Warning" : "warning,警告",
  "❌ Fail" : "fail,失敗",
  "⚡Danger" : "danger,危險",
  "🪲 Bug" : "bug,錯誤",
  "📋 Example" : "example,範例",
  "✍ Quote " : "quote,引用",
  "😝 LOL " : "LOL,哈哈",
  "📕 Reference " : "REF,參考"
};
let keys = Object.keys(list);
key = await tp.system.suggester(keys, keys);
let value = list[key];
let index = value.indexOf(",");
let text = value.substring(index+1);
value = value.substring(0, index);
if (key) return ">[!" + value + "]+ " + text + "\n> ";
%>

3. 範例3-段落形成畫布卡片

  • 功用:將文字段落產生成畫布的卡片

gh|700

<%*
let sCanvasFolder = "030-Inbox/";

//d = tp.file.content.split("\n\n");
let sSelection = tp.file.selection();
let aLines =  sSelection.split("\n\n");
aNodes = [];
let iWidth = 320, iHeight = 160;
for (i = 0;i < aLines.length;i++){
  a = {};
  a.id = i;
  a.x = (i%3) * (iWidth+20);
  a.y = (parseInt(i / 3) % 3) * (iHeight+20);
  a.width = iWidth;
  a.height = iHeight;
  a.type = "text";
  a.text = aLines[i];
  if (a.text.length > 0) {
    aNodes.push(JSON.stringify(a));
  }
}
let sJson = '{"nodes":[' + aNodes.join(",") + ']}';
let sBasename = sCanvasFolder + tp.file.title;
let sFullFilename = sBasename + ".canvas";
let sPath = app.vault.getAbstractFileByPath(sFullFilename);

// 檔名可能重覆,加上序號處理
let k = 1;
while(sPath){
  sFullFilename = sBasename + " " + (k++) + ".canvas";
  sPath = app.vault.getAbstractFileByPath(sFullFilename);
}
sPath = await app.vault.create(sFullFilename, sJson);
await app.workspace.activeLeaf.openFile(sPath);
return null;  // 不回傳null或sSelection的話,原來的選取內容會被刪除
-%>

4. 用Dataviewjs列出所有命令代碼

  • 用Dataviewjs列出所有命令以找到需要使用的命令代碼

gh|700

```dataviewjs
const getNestedObject = (nestedObj, pathArr) => {
    return pathArr.reduce((obj, key) =>
        (obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
}

function getHotkey(arr) {
    return arr.hotkeys ? [[getNestedObject(arr.hotkeys, [0, 'modifiers'])],
    [getNestedObject(arr.hotkeys, [0, 'key'])]].flat(2).join('+').replace('Mod', 'Ctrl') : '–';
}

let cmds = dv.array(Object.entries(app.commands.commands))
    .sort(v => v[1].id, 'asc');

dv.paragraph(cmds.length + " commands currently enabled.<br><br>");

dv.table(["Command ID", "Name in current locale", "Hotkeys"],
    cmds.map(v => [
    v[1].id,
    v[1].name,
    getHotkey(v[1]),
    ])
  );

## 5. Templater Hotkeys命令選單

```js file:"Cmd-All.md"
<%*
let lstCmds = {
  "YAML Type": "templater-obsidian:010-Templates/Cmd-YAML type.md",
  "Week Review": "templater-obsidian:010-Templates/Cmd-Review.md" ,
  "Callout": "templater-obsidian:010-Templates/Cmd-Callout.md",
  "Prepend Line": "templater-obsidian:010-Templates/Cmd-Prepend Line.md",
  "Text to Canvas": "templater-obsidian:010-Templates/Cmd-Insert into canvas.md"
};
let keys = Object.keys(lstCmds);

let key = await tp.system.suggester(keys, keys);
if (!key) return;
let editor = app.workspace.activeLeaf.view.editor;
let position = editor.getCursor();
let text = editor.getLine(position.line);
app.commands.executeCommandById(lstCmds[key]);
-%>

6. 教學影片

https://youtu.be/U8HDmoQAwts

##

您可能也會有興趣的類似文章


Viewing all articles
Browse latest Browse all 897

Trending Articles