Obsidian Templater Timestamp 250908
作成日: 2025年9月8日
仕様まとめ(Obsidian + Templater)
目的
現在行に [[YYYY-MM-DD]] hh:mm 形式のタイムスタンプを挿入。
先頭にスペース・タブ、箇条書き記号(- * +)、チェックボックス([ ], [x])があっても対応。
既存のタイムスタンプ有無は検出せず、必ず追加(置換)する。
タイムスタンプ仕様
形式: [[YYYY-MM-DD]] hh:mm␠(末尾に半角スペース1つ)
例: [[2025-09-08]] 10:15
処理対象
行頭にスペースやタブがあっても保持
箇条書き(- , * , + )があればその後ろ
チェックボックス(- [ ], - [x])があればその後ろ
上記の直後にタイムスタンプを追加
カーソル位置
本文が無い場合 → 行末へ
カーソルがプレフィックス部分(インデント・箇条書き・チェックボックス内)にある場合 → タイムスタンプ直後へ移動
本文がある場合 → 相対位置を維持(タイムスタンプ分だけ右にシフト)
code:js
<%*
// 現在行のプレフィックス(インデント/箇条書き/チェックボックス)の直後に
// "YYYY-MM-DD hh:mm " を常に挿入し、カーソル位置を自然に調整。
// 対応: 先頭スペース/タブ, "-", "*", "+", チェックボックス(- , - x) function addTimestampToCurrentLine() {
// タイムスタンプ作成
const now = new Date();
const yyyy = now.getFullYear();
const mm = String(now.getMonth() + 1).padStart(2, "0");
const dd = String(now.getDate()).padStart(2, "0");
const hh = String(now.getHours()).padStart(2, "0");
const mi = String(now.getMinutes()).padStart(2, "0");
const timestamp = [[${yyyy}-${mm}-${dd}]] ${hh}:${mi} ;
// エディタ取得(MarkdownViewを使わない)
const leaf = app.workspace.activeLeaf;
const view = leaf?.view;
const editor = view?.editor || view?.sourceMode?.cmEditor; // CM6 / 旧CM 互換
if (!editor) { new Notice("Editor not found"); return; }
const cur = editor.getCursor();
const lineText = editor.getLine(cur.line);
const originalCh = cur.ch;
// 先頭構造を抽出:インデント / 箇条書き / チェックボックス / 残り
const re = /^(\s*)(?:(*\-+)\s*)?(?:\[\s*(xX?)\s*\]\s*)?(.*)$/; const m = lineText.match(re);
if (!m) {
// 万一マッチしない場合は先頭に挿入
const newLine = timestamp + lineText;
editor.replaceRange(newLine, { line: cur.line, ch: 0 }, { line: cur.line, ch: lineText.length });
const newCh = originalCh === 0 ? timestamp.length : originalCh + timestamp.length;
editor.setCursor({ line: cur.line, ch: Math.min(newCh, newLine.length) });
return;
}
const bullet = m2 ? (m2 + " ") : ""; // チェックボックスが存在する場合のみ生成(未チェックは空文字が入る)
const checkbox = (m3 !== undefined) ? [${m[3] || " "}] : ""; // プレフィックス(インデント + 箇条書き + チェックボックス)
const prefix = indent + bullet + checkbox;
const insertCol = prefix.length;
// 新しい行
const newLine = prefix + timestamp + rest;
// 置換
editor.replaceRange(newLine, { line: cur.line, ch: 0 }, { line: cur.line, ch: lineText.length });
// カーソル移動ロジック
let newCh;
if (rest.length === 0) {
// 本文が無ければ行末へ
newCh = newLine.length;
} else if (originalCh <= insertCol) {
// プレフィックス内にいた場合はタイムスタンプ直後へ
newCh = insertCol + timestamp.length;
} else {
// それ以外は相対位置を維持(タイムスタンプ分だけ右へシフト)
newCh = originalCh + timestamp.length;
}
editor.setCursor({ line: cur.line, ch: Math.min(newCh, newLine.length) });
}
addTimestampToCurrentLine();
%>