#Obsidian #Templater
> [!caution]
> 2022-02-12時点でのスクリプトは実装が変わっている
## 経緯
[[Minerva]]で[[📓Change logの書き方]]をルールとして定めたが、追加の度に若干面倒に感じる部分がある。更新内容の入力以外はショートカットキー一発で入力できるようにしたい。
## 完成イメージ
![[2021-11-06.gif]]
## やり方
[[Templater]]で以下のスクリプトを作成する。
```js
<%*
const HEADER = "**💽Change log**"
const date = tp.date.now("YYYY/MM/DD")
const tag = `#${date}`
const editor = app.workspace.activeLeaf.view.editor
const index = await tp.user.insert_new_line_at_word_found(HEADER, `\n- ${tag} `)
if (index !== undefined) {
editor.setCursor(index + 1)
const pos = {line: index + 1}
editor.scrollIntoView({from: pos, to: pos}, 200)
return
}
const noteBody = `
---
${HEADER}
- ${tag} 作成
`
const lastLineIndex = await tp.user.insert_new_line_at_last(noteBody)
editor.setCursor(lastLineIndex)
const pos = {line: lastLineIndex}
editor.scrollIntoView({from: pos, to: pos}, 200)
%>
```
`tp.user.insert_new_line_at_last`と`tp.user.insert_new_line_at_word_found`の部分は[[Script User Functions]]を使っている。実装は以下の通り。
```js:insert_new_line_at_last.js
/**
* 最終行にテキストを追加する
* 最終行が空でない場合は新規に行を追加する
* @param {*} text
*
* @returns {Promise<number | undefined>} 挿入した行index (未挿入ならundefined)
*/
async function insertNewLineAtLast(text) {
const editor = app.workspace.activeLeaf.view.editor;
const lastLineIndex = editor.lastLine();
const lastLineText = editor.getLine(lastLineIndex);
const insertedText = lastLineText ? `\n${text}` : text;
editor.replaceRange(insertedText, CodeMirror.Pos(lastLineIndex));
return lastLineIndex + 1;
}
module.exports = insertNewLineAtLast;
```
```js:insert_new_line_at_word_found.js
/**
* 指定された文字列と一致する行の次の行にテキストを追加する
* @param {string} query
* @param {string} text
*
* @returns {Promise<number | undefined>} 挿入した行index (未挿入ならundefined)
*/
async function insertNewLineAtWordFound(query, text) {
const editor = app.workspace.activeLeaf.view.editor;
let rowIndexFound = -1;
for (let row = 0; row <= editor.lastLine(); row++) {
if (editor.getLine(row) === query) {
rowIndexFound = row;
}
}
if (rowIndexFound !== -1) {
editor.replaceRange(text, CodeMirror.Pos(rowIndexFound + 1));
}
return rowIndexFound === -1 ? undefined : rowIndexFound + 1;
}
module.exports = insertNewLineAtWordFound;
```
自分が正常系で使えればいいので例外処理などは適当。